Web框架——Flask系列之請求上下文與應用上下文&請求鉤子&Flask-Script擴展命令行(十七)

一、請求上下文和應用上下文

在這裏插入圖片描述

  1. 請求上下文(request context)
    request和session都屬於請求上下文對象。

  2. 應用上下文(application context)
    current_app和g都屬於應用上下文對象。
    current_app:表示當前運行程序文件的程序實例。
    g:處理請求時,用於臨時存儲的對象,每次請求都會重設這個變量

二、請求鉤子

請求鉤子是通過裝飾器的形式實現,Flask支持如下四種請求鉤子:

  1. before_first_request:在處理第一個請求前運行。
@app.before_first_request
  1. before_request:在每次請求前運行。

  2. after_request(response):如果沒有未處理的異常拋出,在每次請求後運行。

  3. teardown_request(response):在每次請求後運行,即使有未處理的異常拋出。

from flask import Flask,session
app = Flask(__name__)
@app.route("/index",methods=["GET","POST"])
def index():
    print("index 被執行")
    return "index page"
# 四種鉤子函數
@app.before_first_request
def handle_before_first_request():
    '''在第一次請求處理之前先被執行'''
    print("handle_before_first_request 被執行")
@app.before_request
def handle_before_request():
    '''在每次請求之前都被執行'''
    print("handle_before_request 被執行")
@app.after_request
def handle_after_request(response):
    '''每次請求(視圖函數處理)之後都被執行,前提是視圖函數中沒有出現異常'''
    print("handle_after_request 被執行")
    return response
@app.teardown_request
def handle_teardown_request(response):
    '''無論視圖函數中有沒有出現異常,每次請求(視圖函數處理)之後都被執行'''
    print("handle_teardown_request 被執行")
    return response
if __name__ == '__main__':
    app.run(debug=True)

在這裏插入圖片描述

通過判斷請求路徑url 來讓鉤子函數根據視圖的不同執行不同的處理函數:

from flask import Flask,request,url_for
app = Flask(__name__)
@app.route("/index",methods=["GET","POST"])
def index():
    print("index 被執行")
    # a=1/0
    return "index page"

@app.route("/hello")
def hello():
    print("hello 被執行")
    return "hello page"


# 四種鉤子函數
@app.before_first_request
def handle_before_first_request():
    '''在第一次請求處理之前先被執行'''
    print("handle_before_first_request 被執行")
@app.before_request
def handle_before_request():
    '''在每次請求之前都被執行'''
    print("handle_before_request 被執行")
@app.after_request
def handle_after_request(response):
    '''每次請求(視圖函數處理)之後都被執行,前提是視圖函數中沒有出現異常'''

    print("handle_after_request 被執行")
    return response

@app.teardown_request
def handle_teardown_request(response):
    '''無論視圖函數中有沒有出現異常,每次請求(視圖函數處理)之後都被執行'''
    path = request.path
    if path == url_for("index"):
        print("這是在請求鉤子中,判斷請求的視圖邏輯:index")
    elif path == url_for("hello"):
        print("這是在請求鉤子中,判斷請求的視圖邏輯:hello")
    print("handle_teardown_request 被執行")
    return response

if __name__ == '__main__':
    app.run(debug=True)

在這裏插入圖片描述

三、Flask-Script擴展命令行

pip install Flask-Script
在這裏插入圖片描述

from flask import Flask
from flask_script import Manager

app = Flask(__name__)

manager = Manager(app)

@app.route('/')
def index():
    return '牀前明月光'

if __name__ == "__main__":
    manager.run()    ...

Terminal 終端中運行:
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章