Flask中特殊裝飾器的使用
(1)@app.before_request
請求到達視圖函數之前,進行自定義操作,類似django中間件中的process_request,在app中使用則為全局,在藍圖中使用則針對當前藍圖
注意正常狀態(tài)下return值必須為None
(2)@app.after_request
響應返回到達客戶端之前,進行自定義操作,類似jango中間件中的process_response,在app中使用則為全局,在藍圖中使用則針對當前藍圖
注意正常狀態(tài)下視圖函數必須定義一個形參接收response對象,并通過return response返回
(3)@app.errorhandler()
錯誤狀態(tài)碼捕獲執(zhí)行函數,裝飾器參數務必是4xx或者5xx的int型錯誤狀態(tài)碼
(4) @app.template_global() :定義裝飾全局模板可用的函數,直接可在模板中進行渲染使用
@app.template_filter(): 定義裝飾全局模板可用的過濾器函數,類似django中的自定義過濾器,直接可在模板中使用
這兩個特殊裝飾器主要用在模板渲染?。?!
import apps
from flask import request, session, redirect
app = apps.create_app()
@app.before_request
def before1():
print("before1", request)
@app.before_request
def before2():
print("before2")
if request.path == "/":
return None
else:
#這里拋出了一個異常,會被@app.errorhandler(Exception)
# 捕獲到。
raise Exception("hahaha")
@app.before_request
def before3():
print("before3")
@app.after_request
def after1(res):
print("after1")
return res
@app.after_request
def after2(res):
print("after2")
return res
@app.after_request
def after3(res):
print("after3")
return res
# 處理異常,接受參數,可以重定向到指定頁面
@app.errorhandler(Exception)
def error(e):
print("error")
return redirect("/")
@app.route("/login")
def login():
print("login")
return "login"
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()到此這篇關于Flask中特殊裝飾器的使用的文章就介紹到這了,更多相關Flask 特殊裝飾器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
numpy中數組拼接、數組合并方法總結(append(),?concatenate,?hstack,?vstack
numpy庫是一個高效處理多維數組的工具,可以在進行邊寫的數組計算上進行一系列的操作,下面這篇文章主要給大家介紹了關于numpy中數組拼接、數組合并方法(append(),?concatenate,?hstack,?vstack,?column_stack,?row_stack,?np.r_,?np.c_等)的相關資料,需要的朋友可以參考下2022-08-08

