日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Flask中特殊裝飾器的使用_python

作者:雙天至尊-王天龍 ? 更新時(shí)間: 2023-06-17 編程語言

(1)@app.before_request

請(qǐng)求到達(dá)視圖函數(shù)之前,進(jìn)行自定義操作,類似django中間件中的process_request,在app中使用則為全局,在藍(lán)圖中使用則針對(duì)當(dāng)前藍(lán)圖

注意正常狀態(tài)下return值必須為None

(2)@app.after_request

響應(yīng)返回到達(dá)客戶端之前,進(jìn)行自定義操作,類似jango中間件中的process_response,在app中使用則為全局,在藍(lán)圖中使用則針對(duì)當(dāng)前藍(lán)圖

注意正常狀態(tài)下視圖函數(shù)必須定義一個(gè)形參接收response對(duì)象,并通過return response返回

(3)@app.errorhandler()

錯(cuò)誤狀態(tài)碼捕獲執(zhí)行函數(shù),裝飾器參數(shù)務(wù)必是4xx或者5xx的int型錯(cuò)誤狀態(tài)碼

(4) @app.template_global() :定義裝飾全局模板可用的函數(shù),直接可在模板中進(jìn)行渲染使用

@app.template_filter(): 定義裝飾全局模板可用的過濾器函數(shù),類似django中的自定義過濾器,直接可在模板中使用

這兩個(gè)特殊裝飾器主要用在模板渲染?。。?/p>

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:
        #這里拋出了一個(gè)異常,會(huì)被@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
  
# 處理異常,接受參數(shù),可以重定向到指定頁面
@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()

原文鏈接:https://blog.csdn.net/wtl1992/article/details/129187432

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新