在Flask Web应用程序中使用原始SQL对数据库执行CRUD操作可能很繁琐。相反, SQLAlchemy ,Python工具包是一个强大的OR Mapper,它为应用程序开发人员提供了SQL的全部功能和灵活性。Flask-SQLAlchemy是Flask扩展,它将对SQLAlchemy的支持添加到Flask应用程序中。
ORM(Object Relation Mapping,对象关系映射)
先说说定义, 大多数编程语言平台是面向对象的。另一方面,RDBMS服务器中的数据存储为表。
对象关系映射是将对象参数映射到底层RDBMS表结构的技术。
ORM API提供了执行CRUD操作的方法,而不必编写原始SQL语句。
使用SQLAlchemy构建一个小型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对象的所有持久性操作。
以下session方法执行CRUD操作:
db.session.add (模型对象) - 将记录插入到映射表中
db.session.delete (模型对象) - 从表中删除记录
model.query.all() - 从表中检索所有记录(对应于SELECT查询)。
您可以通过使用filter属性将过滤器应用于检索到的记录集。例如,要在学生表中检索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 例子</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>姓名</th> <th>城市</th> <th>详细地址</th> <th>邮编</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.city }}</td> <td>{{ student.addr }}</td> <td>{{ student.postcode }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
上述网页包含指向'/new' URL映射new()函数的超链接。单击时,将打开“学生信息”表单。 数据在 POST方法中发布到相同的URL。
new.html 源码
<!DOCTYPE html> <html> <body> <h3>表单表单表单</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="姓名"/> <br> <label for="city">城市</label><br> <input type="text" name="city" placeholder="城市"/> <br> <label for="addr">地址</label><br> <textarea name="addr" placeholder="详细地址"></textarea> <br> <label for="postcode">邮编</label><br> <input type="text" name="postcode" placeholder="邮编"/> <br> <input type="submit" value="submit" /> </form> </body> </html>
当http方法被检测为POST时,表单数据被添加到学生表中,并且应用返回到显示添加数据的主页。
@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_templatefrom flask_sqlalchemy import SQLAlchemy 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)
从shell运行上述脚本,并在浏览器中输入http://localhost:5000/。如果你搞对了, 正常页面上会看到一个信息表单, 点击“添加学生”链接以打开学生信息表单。填写表单并提交。页面将重新显示提交的数据。