Flask 中的 特殊裝飾器before_request/after_request


 

before_request :在請求收到之前綁定一個函數做一些事情。 
after_request: 每一個請求之后綁定一個函數,如果請求沒有異常。 
teardown_request: 每一個請求之后綁定一個函數,即使遇到了異常。

@app.before_request		在請求進入視圖函數之前做出響應
@app.after_request		在請求結束視圖函數之后 - 響應返回客戶端之前

@app.before_request
def be1():
	return None

@app.after_request
def af1(res):
	return res

正常執行順序: be1 - be2 - be3 - views - af3 - af2 - af1
異常執行順序:be1 - af3 - af2 - af1

@app.errorhandler(404)	重定義錯誤提示
def error404(args) args:錯誤信息

 

使用before_request來做權限和用戶檢查

因為使用restful方式,因此每次用戶訪問都會上傳帶入auth_key,如jwt等,因此可在@app.before_request中做權限的檢查。

@app.app.before_request
def before_request(): #可在此處檢查jwt等auth_key是否合法, #abort(401) #然后根據endpoint,檢查此api是否有權限,需要自行處理 #print(["endpoint",connexion.request.url_rule.endpoint]) #abort(401) #也可做ip檢查,以阻擋受限制的ip等

這樣,可對權限做集中管理

 

在最路由之前添加before_request,打印請求參數可以起到“攔截器”的作用

# @app.before_request 等同下面的 application.before_request

@application.before_request
def print_request_info():
    print("請求地址:" + str(request.path))
    print("請求方法:" + str(request.method))
    print("---請求headers--start--")
    print(str(request.headers).rstrip())
    print("---請求headers--end----")
    print("GET參數:" + str(request.args))
    print("POST參數:" + str(request.form))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM