Code前端首页关于Code前端联系我们

Flask 新手教程:SQLAlchemy的 ORM 技术

terry 2年前 (2023-09-24) 阅读数 56 #后端开发

在 Flask Web 应用程序中使用原始 SQL 执行数据库 CRUD 操作可能会很乏味。相比之下,Python 工具包 SQLAlchemy 是一个功能强大的 OR 映射器,可为应用程序开发人员提供 SQL 的全部功能和灵活性。 Flask-SQLAlchemy 是 Fl​​ask 扩展,为 Flask 应用程序添加 SQLAlchemy 支持。

什么是ORM(对象关系映射)?

大多数编程语言平台都是面向对象的。另一方面,RDBMS服务器上的数据以表格形式存储。对象关系映射是一种将对象参数映射到底层 RDBMS 表结构的技术。 ORM API 提供了无需编写原始 SQL 语句即可执行 CRUD 操作的方法。

在这一部分中,我们将学习使用 Flask - SQLAlchemy 的 ORM 技术并创建一个小型 Web 应用程序。

步骤 1 - 安装 Flask-SQLAlchemy 扩展。

pip install flask-sqlalchemy
Shell

步骤 2 - 需要从此模块导入类 SQLAlchemy

from flask_sqlalchemy import SQLAlchemy
Python

第 3 步 - 现在创建一个 Flask 应用程序对象并设置要使用的数据库的 URI。

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

步骤 4 - 然后使用应用程序对象作为参数创建 SQLAlchemy 类的对象。该对象包含 ORM 操作的辅助函数。它还提供了一个父模型类,在其中声明用户定义的模型。下面的代码片段创建了一个学生模型。

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() 方法。

db.create_all()
Python

SQLAlchemy 的 Session 对象控制 ORM 对象上的所有持久化操作。

以下会话方法执行 CRUD 操作 -

  • db.session.add(模型对象)- 将记录插入到映射表中
  • db.session.delete(模型对象)- 从表中删除记录
  • model.query.all() - 获取表中的所有记录(相当于 SELECT 查询)。

可以使用 filter 属性将过滤器应用于搜索到的记录集。例如,如果你想获取表studentscity = '海口'的记录,请使用以下语句 -

Students.query.filter_by(city = 'Haikou').all()
现在有了这些知识Pyth我们的应用程序将有一个显示功能添加有关学生的数据。应用程序

的入口点是绑定到 URL => ‘/’ 的函数 show_all()。学生记录文件作为参数传递给 HTML 模板。模板中的服务器端代码呈现 HTML 表中的记录。

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

模板 (show_all.html) 的 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>
上述 URL 包含指向 HTML: new 的链接映射函数 new() 的超链接。单击后,将打开一个包含学生信息的表格。数据在 POST 方法中发送到相同的 URL。模板文件

new.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>
HTMLHTML

当POST中发现嵌入http方法时,插入表单数据学生,应用程序返回到显示数据的主页。

@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)。 ?添加链接”以打开学生信息表。

Flask菜鸟教程:SQLAlchemy的ORM技术

填写表格并提交,提交的数据将在首页列出。操作完成后,您将看到如下所示的输出。
Flask菜鸟教程:SQLAlchemy的ORM技术

//阅读更多:https://www.yiibai.com/flask/flask_sqlalchemy.html

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门