在Flask Web应用程序中使用原始SQL对数据库执行CRUD操作可能很乏味。 相反,Python工具包SQLAlchemy是一个功能强大的OR映射器,为应用程序开发人员提供了SQL的全部功能和灵活性。 Flask-SQLAlchemy是Flask扩展,它将对SQLAlchemy的支持添加到Flask应用程序中。
什么是ORM(对象关系映射)?
大多数编程语言平台是面向对象的。 另一方面,RDBMS服务器中的数据以表格形式存储。 对象关系映射是一种将对象参数映射到底层RDBMS表结构的技术。 ORM API提供了执行CRUD操作的方法,而无需编写原始SQL语句。
在本节中,我们将学习使用Flask-SQLAlchemy的ORM技术并构建一个小型Web应用程序。
第1步 - 安装Flask-SQLAlchemy扩展。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08pip install flask-sqlalchemy
第2步 - 需要从该模块导入SQLAlchemy类。
示例
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08from flask_sqlalchemy import SQLAlchemy
第3步 - 现在创建一个Flask应用程序对象并为要使用的数据库设置URI。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
第4步 - 然后用应用程序对象作为参数创建一个SQLAlchemy类的对象。 该对象包含ORM操作的辅助函数。 它还提供了一个使用其声明用户定义模型的父级模型类。 在下面的代码片段中,创建了一个学生模型。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08db = 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()方法。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08db.create_all()
SQLAlchemy的Session对象管理ORM对象的所有持久性操作。
以下会话方法执行CRUD操作 -
db.session.add(模型对象) - 将一条记录插入到映射表中db.session.delete(模型对象) - 从表中删除记录model.query.all() - 从表中检索所有记录(对应于SELECT查询)。
可以使用filter属性将筛选器应用于检索到的记录集。例如,要在students表中检索city ='Haikou'的记录,请使用以下语句 -
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08Students.query.filter_by(city = 'Haikou').all()
有了这么多的背景知识,现在我们将为我们的应用程序提供视图函数来添加学生数据。
应用程序的入口点是绑定到URL => ‘/‘的show_all()函数。学生的记录集作为参数发送给HTML模板。 模板中的服务器端代码以HTML表格形式呈现记录。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08@app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all() )
模板的HTML脚本( show_all.html)就像这样 -
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08 Flask示例 学生列表 - Flask SQLAlchemy示例
{%- for message in get_flashed_messages() %} {{ message }} {%- endfor %} 学生 (添加 )
姓名 城市 地址 Pin {% for student in students %} {{ student.name }} {{ student.city }} {{ student.addr }} {{ student.pin }} {% endfor %}
上面的页面包含一个指向URL:/new 映射new()函数的超链接。点击后,它会打开一个学生信息表单。 数据在POST方法中发布到相同的URL。
模板文件: new.html 的代码如下 -
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08 Flask示例 学生信息 - Flask SQLAlchemy示例
{%- for category, message in get_flashed_messages(with_categories = True) %} {{ message }} {%- endfor %}
当检测到http方法为POST时,表单数据将插入到students表中,并且应用程序返回到显示数据的主页。
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08@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)。
示例
# Filename : example.py# Copyright : 2020 By Nhooo# Author by : www.cainiaojc.com# Date : 2020-08-08from 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 shell运行脚本,并在浏览器中输入:http://localhost:5000/ ,显示结果如下 -
点击“ 添加”链接打开学生信息表单。
填写表单并提交,主页将提交的数据列出来。操作之后,将看到如下所示的输出。
留言与评论(共有 0 条评论) “” |