常用鈎子函數
在Flask中鈎子函數是使用特定的裝飾器裝飾的函數。鈎子函數可以在正常執行的代碼中,插入一段自己想要執行的代碼。那么這種函數就叫做鈎子函數。(hook)
- before_first_request:顧名思義,注冊一個在處理第一個請求之前運行的函數
@app.before_first_request # 第一次訪問的時候調用 def first_request(): print('first time request')
- before_request:注冊一個在處理請求之前運行的函數。
@app.before_request # 每次接受到請求的時候都會執行 def before_request(): if not hasattr(g,'user'): setattr(g,'user','xxxx')
-
teardown_appcontext:不管是否有異常,注冊的函數都會在每次請求之后執行。
@app.teardown_appcontext def teardown(exc=None): if exc is None: db.session.commit() else: db.session.rollback() db.session.remove()
- template_filter:在使用Jinja2模板的時候自定義過濾器。比如可以增加一個upper的過濾器
@app.template_filter def upper_filter(s): return s.upper()
- `context_processor`:必須返回一個字典。這個字典中的值在所有模版中都可以使用。這個鈎子函數的函數是,如果一些在很多模版中都要用到的變量,那么就可以使用這個鈎子函數來返回,而不用在每個視圖函數中的`render_template`中去寫,這樣可以讓代碼更加簡潔和好維護。
@app.context_processor def my_context_processor(): return {'current_user':'xxx'}
- `errorhandler`:在發生一些異常的時候,比如404錯誤,比如500錯誤。可以使用`errorhandler`來出來。需要注意幾點:
* 在errorhandler裝飾的鈎子函數下,記得要返回相應的狀態碼。
* 在errorhandler裝飾的鈎子函數中,必須要寫一個參數,來接收錯誤的信息,如果沒有參數,就會直接報錯。
* 使用`flask.abort`可以手動的拋出相應的錯誤,比如開發者在發現參數不正確的時候可以自己手動的拋出一個400錯誤。
@app.errorhandler(404) def page_not_found(error): return 'This page does not exist',404

from flask import abort def my_list(): # 如果user_id在數據庫中不存在,這時候我就讓他跳轉到400錯誤 abort(400) # 拋出400錯誤
g對象
g綁定到了Local對象,是線程隔離的。該對象的作用是綁定數據,綁定的數據可以在全局使用!
@app.route('/') def index(): username = request.args.get('username')
g.username = username # 綁定
log_a()
log_b()
log_c(
from flask import g def log_a(): print('log a %s' % g.username) def log_b(): print('log b %s' % g.username) def log_c(): print('log c %s' % g.username)