SQLAlchemy是flask的擴展,是一個功能強大的OR映射器,支持多種數(shù)據(jù)庫后臺,可以將類的對象映射至數(shù)據(jù)庫表。
使用這個工具,可以創(chuàng)建數(shù)據(jù)庫,創(chuàng)建表,并為數(shù)據(jù)庫添加數(shù)據(jù),進行查詢操作等。
參考:Flask SQLAlchemy - Flask 教程 | BootWiki.com
創(chuàng)建實例?
?app=Flask(__name__)? #創(chuàng)建Flask實例
?app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'#設置數(shù)據(jù)庫URL
app.config[]可以為Flask實例添加一些配置。
這個配置指明當前文件夾下students.sqlite3數(shù)據(jù)庫文件作為數(shù)據(jù)庫訪問的URL,這個數(shù)據(jù)庫文件當前可以不存在,在程序運行時create。
在Flask-SQLAlchemy中,數(shù)據(jù)庫使用URL指定。幾種最流行的數(shù)據(jù)庫引擎使用的URL格式
?
?
app.config['SECRET_KEY'] = "random string"
?這個配置設置了secret_key,用于session,在學習session的時候已經(jīng)知道,服務器加密會話數(shù)據(jù)時需要一個secret_key,至于這里為什么要用到session,在后面會說到。
db=SQLAlchemy(app)?創(chuàng)建一個SQLAlchemy類的對象。 該對象包含ORM操作的輔助函數(shù)。 它還提供了一個使用其聲明用戶定義模型的父級模型類。
類和模型?
模型這個術語表示應用使用的持久化實體。在ORM中,模型一般是一個Python類,類中的屬性對應于數(shù)據(jù)庫表中的列。
定義一個類(students模型),繼承Model模型。這個類和數(shù)據(jù)庫的表對應,類的屬性分別對應表的字段。
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
db.Column類構造函數(shù)的第一個參數(shù)是數(shù)據(jù)庫列和模型屬性的類型?
常用的類型
?
db.Column的其余參數(shù)指定屬性的配置選項
常用的SQLAlchemy配置選項?
?
通過屬性定義,也為表添加了字段。id為主鍵。
db.create_all()
使用這個語句,執(zhí)行創(chuàng)建數(shù)據(jù)庫操作。
CRUD操作?
?SQLAlchemy的Session對象管理ORM對象的所有持久性操作。
db.session.add(模型對象) - 將一條記錄插入到映射表中? ?準備把對象寫入數(shù)據(jù)庫之前,要先將其添加到會話中
db.session.delete(模型對象) - 從表中刪除記錄
模型.query.all() - 從表中檢索所有記錄(對應于SELECT查詢)。db.session.commit()提交修改??為了把對象寫入數(shù)據(jù)庫,我們要調(diào)用commit()方法提交會話
可以使用filter屬性將篩選器應用于檢索到的記錄集。例如,要在students表中檢索city ='Haikou'的記錄,請使用以下語句?
Students.query.filter_by(city = 'Haikou').all()
?
?
?
?
數(shù)據(jù)庫會話db.session和Flask的session對象沒有關系。數(shù)據(jù)庫會話也稱為事務,?能保證數(shù)據(jù)庫的一致性。提交操作使用原子方式把會話中的對象全部寫入數(shù)據(jù)庫。如果在寫入會話的過程中發(fā)生了錯誤,那么整個會話都會失效。如果你始終把相關改動放在會話中提交,就能避免因部分更新導致的數(shù)據(jù)庫不一致。
實戰(zhàn)
實現(xiàn)一個添加學生信息并展示信息的小應用。
點擊添加學生,打開添加學生頁面,提交信息后,展示所有學生信息列表。
http://localhost:5000/
http://localhost:5000/new
?
http://localhost:5000/?
這個應用,一共有兩個頁面,一個展示所有信息show_all.html,一個添加學生信息new.html。
在展示所有信息頁面,首先顯示閃現(xiàn)消息flash,當沒有閃現(xiàn)消息的時候不顯示。添加學生鏈接至new頁面,最下方讀取數(shù)據(jù)庫數(shù)據(jù)并顯示,數(shù)據(jù)庫無數(shù)據(jù)時不顯示數(shù)據(jù)。
show_all.html如下
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
<body>
<h1>
Flask
SQLAlchemy示例
</h1>
<hr/>
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}
<h1>(<a href = "{{ url_for('new') }}">添加學生
</a>)</h1>
<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>
對于的視圖函數(shù)如下
@app.route('/')
def show_all():
return render_template('show_all.html',students=students.query.all())
添加學生信息頁面new.html,也會顯示flash,下放展示一個表單,點擊提交按鈕后,表單數(shù)據(jù)以post方式提交給服務器,并使用視圖函數(shù)new接收表單數(shù)據(jù)進行處理。對表單數(shù)據(jù)進行校驗,不滿足校驗顯示flash,滿足校驗,則向數(shù)據(jù)庫添加數(shù)據(jù),并重定向至展示信息頁面。
new.html頁面如下:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
<h3>添加學生信息</h3>
<hr/>
{%- for category, message in get_flashed_messages(with_categories = true) %}
<div class = "alert alert-danger">
{{ message }}
</div>
{%- endfor %}
<form action = "/new" 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"></textarea><br>
<label for = "PIN">郵編</label><br>
<input type = "text" name = "pin" placeholder = "pin" /><br>
<input type = "submit" value = "提交" />
</form>
</body>
</html>
?對于視圖函數(shù)如下
@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') #如果有一個沒填寫,閃現(xiàn)消息
else:
student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin'])
print(student)
db.session.add(student)#把數(shù)據(jù)添加到數(shù)據(jù)庫
db.session.commit()#提交數(shù)據(jù)
flash('Record was successfully added')#閃現(xiàn)消息添加成功
return redirect(url_for('show_all')) #一個函數(shù)可以有兩個return
return render_template('new.html') #點擊添加按鈕,渲染new.html頁面
最后附上程序入口,運行程序,即可訪問。
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
完整代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-408070.html
from flask_sqlalchemy import SQLAlchemy
from flask import Flask,render_template,request,flash,redirect,url_for
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'#設置數(shù)據(jù)庫URL
#創(chuàng)建一個SQLAlchemy類的對象。 該對象包含ORM操作的輔助函數(shù)。 它還提供了一個使用其聲明用戶定義模型的父級模型類。
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():
db.create_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') #如果有一個沒填寫,閃現(xiàn)消息
else:
student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin'])
print(student)
db.session.add(student)#把數(shù)據(jù)添加到數(shù)據(jù)庫
db.session.commit()#提交數(shù)據(jù)
flash('Record was successfully added')#閃現(xiàn)消息添加成功
return redirect(url_for('show_all')) #一個函數(shù)可以有兩個return
return render_template('new.html') #點擊添加按鈕,渲染new.html頁面
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
?總結:文本學習了Flask數(shù)據(jù)庫相關擴展SQLAlchemy的使用,并實現(xiàn)了一個添加并展示學生信息的應用。
?文章來源地址http://www.zghlxwxcb.cn/news/detail-408070.html
到了這里,關于Flask-數(shù)據(jù)庫-SQLAlchemy的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!