flask-鉤子函數&g對象

經常使用鉤子函數

在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:無論是否有異常,註冊的函數都會在每次請求以後執行。flask

@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對象,是線程隔離的。該對象的做用是綁定數據,綁定的數據能夠在全局使用!session

@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)
相關文章
相關標籤/搜索