Flask菜鸟教程:SQLAlchemy的ORM技术

2023-05-1514:44:13后端程序开发Comments1,711 views字数 4738阅读模式

Flask Web应用程序中使用原始SQL对数据库执行CRUD操作可能很乏味。 相反,Python工具包SQLAlchemy是一个功能强大的OR映射器,为应用程序开发人员提供了SQL的全部功能和灵活性。 Flask-SQLAlchemy是Flask扩展,它将对SQLAlchemy的支持添加到Flask应用程序中。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

什么是ORM(对象关系映射)?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

大多数编程语言平台是面向对象的。 另一方面,RDBMS服务器中的数据以表格形式存储。 对象关系映射是一种将对象参数映射到底层RDBMS表结构的技术。 ORM API提供了执行CRUD操作的方法,而无需编写原始SQL语句。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

在本节中,我们将学习使用Flask-SQLAlchemy的ORM技术并构建一个小型Web应用程序。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

第1步 - 安装Flask-SQLAlchemy扩展。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

pip install flask-sqlalchemy
Shell

第2步 - 需要从该模块导入SQLAlchemy类。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

from flask_sqlalchemy import SQLAlchemy
Python

第3步 - 现在创建一个Flask应用程序对象并为要使用的数据库设置URI。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
Python

第4步 - 然后用应用程序对象作为参数创建一个SQLAlchemy类的对象。 该对象包含ORM操作的辅助函数。 它还提供了一个使用其声明用户定义模型的父级模型类。 在下面的代码片段中,创建了一个学生模型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

db = SQLAlchemy(app)
class students(db.Model):
    id = db.Column('student_id', db.Integer, primary_key = True)
    name = db.Column(db.String(100))
    city = db.Column(db.String(50))  
    addr = db.Column(db.String(200))
    pin = db.Column(db.String(10))

def __init__(self, name, city, addr,pin):
    self.name = name
    self.city = city
    self.addr = addr
    self.pin = pin
Python

第5步 - 要创建/使用URI中提到的数据库,请运行create_all()方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

db.create_all()
Python

SQLAlchemy的Session对象管理ORM对象的所有持久性操作。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

以下会话方法执行CRUD操作 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

  • db.session.add(模型对象) - 将一条记录插入到映射表中
  • db.session.delete(模型对象) - 从表中删除记录
  • model.query.all() - 从表中检索所有记录(对应于SELECT查询)。

可以使用filter属性将筛选器应用于检索到的记录集。例如,要在students表中检索city ='Haikou'的记录,请使用以下语句 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

Students.query.filter_by(city = 'Haikou').all()
Python

有了这么多的背景知识,现在我们将为我们的应用程序提供视图函数来添加学生数据。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

应用程序的入口点是绑定到URL => ‘/‘的show_all()函数。学生的记录集作为参数发送给HTML模板。 模板中的服务器端代码以HTML表格形式呈现记录。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

@app.route('/')
def show_all():
    return render_template('show_all.html', students = students.query.all() )
Python

模板的HTML脚本(show_all.html)就像这样 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
   <body>

      <h3>
         <a href = "{{ url_for('show_all') }}">学生列表 - Flask 
            SQLAlchemy示例</a>
      </h3>

      <hr/>
      {%- for message in get_flashed_messages() %}
         {{ message }}
      {%- endfor %}

      <h3>学生 (<a href = "{{ url_for('new') }}">添加
         </a>)</h3>

      <table>
         <thead>
            <tr>
               <th>姓名</th>
               <th>城市</th>
               <th>地址</th>
               <th>Pin</th>
            </tr>
         </thead>

         <tbody>
            {% for student in students %}
               <tr>
                  <td>{{ student.name }}</td>
                  <td>{{ student.city }}</td>
                  <td>{{ student.addr }}</td>
                  <td>{{ student.pin }}</td>
               </tr>
            {% endfor %}
         </tbody>
      </table>

   </body>
</html>
HTML

上面的页面包含一个指向URL:/new 映射new()函数的超链接。点击后,它会打开一个学生信息表单。 数据在POST方法中发布到相同的URL。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

模板文件:new.html 的代码如下 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
   <body>
    <h3>学生信息 - Flask SQLAlchemy示例</h3>
      <hr/>

      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {{ message }}
         </div>
      {%- endfor %}

      <form action = "{{ request.path }}" method = "post">
         <label for = "name">姓名</label><br>
         <input type = "text" name = "name" placeholder = "Name" /><br>
         <label for = "email">城市</label><br>
         <input type = "text" name = "city" placeholder = "city" /><br>
         <label for = "addr">地址</label><br>
         <textarea name = "addr" placeholder = "addr"/><br>
         <label for = "PIN">城市</label><br>
         <input type = "text" name = "pin" placeholder = "pin" /><br>
         <input type = "submit" value = "提交" />
      </form>

   </body>
</html>
HTML

当检测到http方法为POST时,表单数据将插入到students表中,并且应用程序返回到显示数据的主页。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

@app.route('/new', methods = ['GET', 'POST'])
def new():
    if request.method == 'POST':
       if not request.form['name'] or not request.form['city'] or not request.form['addr']:
         flash('Please enter all the fields', 'error')
       else:
          student = students(request.form['name'], request.form['city'],
             request.form['addr'], request.form['pin'])

          db.session.add(student)
          db.session.commit()

          flash('Record was successfully added')
          return redirect(url_for('show_all'))
    return render_template('new.html')
Python

下面给出的是完整的应用程序代码(app.py)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.config['SECRET_KEY'] = "random string"

db = SQLAlchemy(app)

class students(db.Model):
    id = db.Column('student_id', db.Integer, primary_key = True)
    name = db.Column(db.String(100))
    city = db.Column(db.String(50))
    addr = db.Column(db.String(200)) 
    pin = db.Column(db.String(10))

    def __init__(self, name, city, addr,pin):
        self.name = name
        self.city = city
        self.addr = addr
        self.pin = pin

@app.route('/')
def show_all():
    return render_template('show_all.html', students = students.query.all() )

@app.route('/new', methods = ['GET', 'POST'])
def new():
    if request.method == 'POST':
       if not request.form['name'] or not request.form['city'] or not request.form['addr']:
          flash('Please enter all the fields', 'error')
       else:
          student = students(request.form['name'], request.form['city'],request.form['addr'], request.form['pin'])
          print(student)
          db.session.add(student)
          db.session.commit()
          flash('Record was successfully added')
          return redirect(url_for('show_all'))
    return render_template('new.html')

if __name__ == '__main__':
    db.create_all()
    app.run(debug = True)
Python

从Python shell运行脚本,并在浏览器中输入:http://localhost:5000/ ,显示结果如下 -
Flask菜鸟教程:SQLAlchemy的ORM技术文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

点击“添加”链接打开学生信息表单。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

Flask菜鸟教程:SQLAlchemy的ORM技术文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

填写表单并提交,主页将提交的数据列出来。操作之后,将看到如下所示的输出。
Flask菜鸟教程:SQLAlchemy的ORM技术文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

//更多请阅读:https://www.yiibai.com/flask/flask_sqlalchemy.html文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/39563.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/39563.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定