Flask:06-一首歌的時間掌握flask資料模型(02)
資料模型
模型關係
-
一對多(使用最多)
-
一:學生(Student)
- 需要新增反向引用
-
多:文章(Article)
- 需要新增外來鍵關聯
-
一:學生(Student)
-
一對一
-
一:學生(Student),主表
-
需要新增反向引用,在一對多的情況下多指定屬性
userlist=False
即可
-
需要新增反向引用,在一對多的情況下多指定屬性
-
一:詳情(Profile),次表
- 需要新增外來鍵關聯
-
一:學生(Student),主表
-
多對多
-
多:學生(Student)
secondary db.backref
- 多:課程(Course)
-
中間關聯表:學生選課表,不需要進行操作和維護
- 欄位:表名、外來鍵關聯
-
多:學生(Student)
模型總結
-
等價查詢
@app.route('/query/') def query(): # students = Student.query.all() # 等價於 students = db.session.query(Student).all() return ','.join(s.name for s in students)
-
指定欄位查詢
@app.route('/select/') def select(): # ret = db.session.query(Student.id, Student.name).all() # 指定欄位查詢,等價於上式 ret = Student.query.with_entities(Student.id, Student.name).all() # 返回指定欄位組成的元組構成的列表 print(ret) return '查詢結束'
-
分頁查詢:paginate,專案中講解。
-
檢視SQL日誌:就是檢視執行過的SQL語句。
# 記錄SQL日誌,需要滿足以下三個條件中的任意一個即可 # app.config['DEBUG'] = True # app.config['TESTING'] = True app.config['SQLALCHEMY_RECORD_QUERIES'] = True from flask_sqlalchemy import get_debug_queries queries = get_debug_queries() for q in queries: print(q)
資料快取
-
說明:
資料庫的速度是一個web應用的效能瓶頸,因此,為了提高訪問效率,應該儘可能減少資料庫的訪問。可以將經常訪問的資料快取起來,每次訪問時先從快取中獲取資料,若有直接返回;沒有再從資料庫中讀取。
-
flask-cache:專門負責資料快取的擴充套件。
-
安裝:
pip install flask-cache
-
使用:
from flask_cache import Cache # 配置 # 快取型別 app.config['CACHE_TYPE'] = 'redis' # 主機 app.config['CACHE_REDIS_HOST'] = '127.0.0.1' # 埠 app.config['CACHE_REDIS_PORT'] = 6379 # 資料庫 app.config['CACHE_REDIS_DB'] = 1 # 建立物件 cache = Cache(app, with_jinja2_ext=False)
-
快取檢視函式:
@app.route('/') # timeout:指定快取有效期,預設300s # key_prefix:快取鍵字首,預設:view/ + 路由地址 @cache.cached(timeout=100, key_prefix='index') def index(): print('讀取資料庫') return '有效資料'
-
快取普通函式:
# 快取普通函式,key_prefix必須指定 @cache.cached(timeout=100, key_prefix='common') def common(): print('查詢資料庫') return '返回的資料' @app.route('/hello/') def hello(): return common()
-
清除快取
@app.route('/clear/') def clear(): # 指定刪除 # cache.delete('index') # 全部清空 cache.clear() return '快取已清除'
-
自定義快取
@app.route('/zidingyi/') def zidingyi(): # 先從快取中獲取 data = cache.get('zidingyi_data') if data: return data # 沒有快取資料 print('從資料庫中獲取資料') data = '123456' # 快取資料 cache.set('zidingyi_data', data, timeout=100) return data