- Flask 教程
- Flask - 首页
- Flask - 概述
- Flask - 环境
- Flask - 应用
- Flask - 路由
- Flask - 变量规则
- Flask - URL构建
- Flask - HTTP方法
- Flask - 模板
- Flask - 静态文件
- Flask - 请求对象
- 将表单数据发送到模板
- Flask - Cookie
- Flask - 会话
- Flask - 重定向和错误
- Flask - 消息闪现
- Flask - 文件上传
- Flask - 扩展
- Flask - 邮件
- Flask - WTF
- Flask - SQLite
- Flask - SQLAlchemy
- Flask - Sijax
- Flask - 部署
- Flask - FastCGI
- Flask 有用资源
- Flask - 快速指南
- Flask - 有用资源
- Flask - 讨论
Flask – SQLAlchemy
在 Flask Web 应用中使用原始 SQL 来对数据库执行 CRUD 操作可能很繁琐。相反,SQLAlchemy,一个 Python 工具包,是一个强大的对象关系映射器 (OR Mapper),它为应用程序开发者提供了 SQL 的全部功能和灵活性。Flask-SQLAlchemy 是 Flask 扩展,它为你的 Flask 应用程序添加了对 SQLAlchemy 的支持。
什么是 ORM(对象关系映射)?
大多数编程语言平台都是面向对象的。另一方面,RDBMS 服务器中的数据存储为表。对象关系映射是一种将对象参数映射到底层 RDBMS 表结构的技术。ORM API 提供了执行 CRUD 操作的方法,而无需编写原始 SQL 语句。
在本节中,我们将学习 Flask-SQLAlchemy 的 ORM 技术,并构建一个小型 Web 应用程序。
步骤 1 - 安装 Flask-SQLAlchemy 扩展。
pip install flask-sqlalchemy
步骤 2 - 你需要从该模块导入 SQLAlchemy 类。
from flask_sqlalchemy import SQLAlchemy
步骤 3 - 现在创建一个 Flask 应用程序对象并设置要使用的数据库的 URI。
app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
步骤 4 - 然后使用应用程序对象作为参数创建一个 SQLAlchemy 类的对象。此对象包含用于 ORM 操作的辅助函数。它还提供了一个父 Model 类,用户定义的模型就是使用它声明的。在下面的代码片段中,创建了一个students模型。
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
步骤 5 - 要创建/使用 URI 中提到的数据库,请运行create_all()方法。
db.create_all()
SQLAlchemy 的Session对象管理ORM对象的所有持久性操作。
以下会话方法执行 CRUD 操作:
db.session.add(模型对象) - 将记录插入映射表
db.session.delete(模型对象) - 从表中删除记录
model.query.all() - 从表中检索所有记录(对应于 SELECT 查询)。
你可以使用 filter 属性将过滤器应用于检索到的记录集。例如,为了在 students 表中检索 city = 'Hyderabad' 的记录,请使用以下语句:
Students.query.filter_by(city = ’Hyderabad’).all()
有了这些背景知识,现在我们将为我们的应用程序提供视图函数来添加学生数据。
应用程序的入口点是绑定到'/'URL 的show_all()函数。学生表的记录集作为参数发送到 HTML 模板。模板中的服务器端代码以 HTML 表格形式呈现记录。
@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all() )
模板('show_all.html')的 HTML 脚本如下:
<!DOCTYPE html>
<html lang = "en">
<head></head>
<body>
<h3>
<a href = "{{ url_for('show_all') }}">Comments - Flask
SQLAlchemy example</a>
</h3>
<hr/>
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}
<h3>Students (<a href = "{{ url_for('new') }}">Add Student
</a>)</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Address</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>
上面页面包含一个指向'/new' URL 映射new()函数的超链接。单击后,它将打开一个学生信息表单。数据以POST方法发布到相同的 URL。
new.html
<!DOCTYPE html>
<html>
<body>
<h3>Students - Flask SQLAlchemy example</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">Name</label><br>
<input type = "text" name = "name" placeholder = "Name" /><br>
<label for = "email">City</label><br>
<input type = "text" name = "city" placeholder = "city" /><br>
<label for = "addr">addr</label><br>
<textarea name = "addr" placeholder = "addr"></textarea><br>
<label for = "PIN">City</label><br>
<input type = "text" name = "pin" placeholder = "pin" /><br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
当检测到 http 方法为 POST 时,表单数据将添加到 students 表中,并且应用程序将返回到主页,显示已添加的数据。
@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')
以下是应用程序(app.py)的完整代码。
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'])
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 shell 运行脚本,并在浏览器中输入https://:5000/。
单击“添加学生”链接以打开学生信息表单。
填写表单并提交。主页将重新出现,显示提交的数据。
我们可以看到如下所示的输出。
