在Flask Web應(yīng)用程序中使用原始SQL對(duì)數(shù)據(jù)庫執(zhí)行CRUD操作可能很繁瑣。相反, SQLAlchemy ,Python工具包是一個(gè)強(qiáng)大的OR Mapper,它為應(yīng)用程序開發(fā)人員提供了SQL的全部功能和靈活性。Flask-SQLAlchemy是Flask擴(kuò)展,它將對(duì)SQLAlchemy的支持添加到Flask應(yīng)用程序中。
什么是ORM(Object Relation Mapping,對(duì)象關(guān)系映射)?
大多數(shù)編程語言平臺(tái)是面向?qū)ο蟮摹?/span>另一方面,RDBMS服務(wù)器中的數(shù)據(jù)存儲(chǔ)為表。
對(duì)象關(guān)系映射是將對(duì)象參數(shù)映射到底層RDBMS表結(jié)構(gòu)的技術(shù)。
ORM API提供了執(zhí)行CRUD操作的方法,而不必編寫原始SQL語句。
在本節(jié)中,我們將研究Flask-SQLAlchemy的ORM技術(shù)并構(gòu)建一個(gè)小型Web應(yīng)用程序。
步驟1 - 安裝Flask-SQLAlchemy擴(kuò)展。
pip install flask-sqlalchemy
步驟2 - 您需要從此模塊導(dǎo)入SQLAlchemy類。
from flask_sqlalchemy import SQLAlchemy
步驟3 - 現(xiàn)在創(chuàng)建一個(gè)Flask應(yīng)用程序?qū)ο蟛橐褂玫臄?shù)據(jù)庫設(shè)置URI。
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
步驟4 - 然后使用應(yīng)用程序?qū)ο笞鳛閰?shù)創(chuàng)建SQLAlchemy類的對(duì)象。該對(duì)象包含用于ORM操作的輔助函數(shù)。它還提供了一個(gè)父Model類,使用它來聲明用戶定義的模型。
在下面的代碼段中,創(chuàng)建了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 - 要?jiǎng)?chuàng)建/使用URI中提及的數(shù)據(jù)庫,請(qǐng)運(yùn)行create_all()方法。
db.create_all()
SQLAlchemy的Session對(duì)象管理ORM對(duì)象的所有持久性操作。
以下session方法執(zhí)行CRUD操作:
db.session.add (模型對(duì)象) - 將記錄插入到映射表中
db.session.delete (模型對(duì)象) - 從表中刪除記錄
model.query.all() - 從表中檢索所有記錄(對(duì)應(yīng)于SELECT查詢)。
您可以通過使用filter屬性將過濾器應(yīng)用于檢索到的記錄集。例如,要在學(xué)生表中檢索city ='Hyderabad'的記錄,請(qǐng)使用以下語句:
Students.query.filter_by(city = ’Hyderabad’).all()
有了這么多的背景,現(xiàn)在我們將為我們的應(yīng)用程序提供視圖函數(shù)來添加學(xué)生數(shù)據(jù)。
應(yīng)用程序的入口點(diǎn)是綁定到'/' URL的show_all()函數(shù)。學(xué)生表的記錄集作為參數(shù)發(fā)送到HTML模板。模板中的服務(wù)器端代碼以HTML表格形式呈現(xiàn)記錄。
@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>
上述網(wǎng)頁包含指向'/new' URL映射new()函數(shù)的超鏈接。單擊時(shí),將打開“學(xué)生信息”表單。 數(shù)據(jù)在 POST方法中發(fā)布到相同的URL。
<!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 = "city">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>
當(dāng)http方法被檢測(cè)為POST時(shí),表單數(shù)據(jù)被添加到學(xué)生表中,并且應(yīng)用返回到顯示添加數(shù)據(jù)的主頁。
@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')
下面給出了應(yīng)用程序(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運(yùn)行腳本,并在瀏覽器中輸入http://localhost:5000/。
點(diǎn)擊“添加學(xué)生”鏈接以打開學(xué)生信息表單。
填寫表單并提交。主頁將重新顯示提交的數(shù)據(jù)。
我們可以看到輸出如下所示。
更多建議: