請求擴展、藍圖、g對象

  • 2022 年 5 月 16 日
  • 筆記

今日內容概要

  • 請求擴展
  • 藍圖
  • g對象

內容詳細

1、請求擴展

# 在請求來了,請求走了,可以做一些校驗和攔截,通過裝飾器來實現 7 個

# 1 before_request
	類比django中間件中的process_request,在請求收到之前綁定一個函數做一些事情
    
# 2 after_request

# 3 before_first_request

# 4 teardown_request

# 5 errorhandler

# 6 template_global

# 7 template_filter
from flask import Flask, request, render_template

app = Flask(__name__)


# app.debug = True


# 1. 請求擴展之before_request,在進入視圖函數之前執行,如果有多個,是從上往下執行
@app.before_request
def before():
    # 判斷是否登錄,如果登錄了繼續往下走,如果沒登陸
    # request.xxx='lqz'  可以往請求中放值,後續可以取出來,只針對於當次請求有效
    print("我執行了1111")


# @app.before_request  # 多個before_request 從上往下 只執行一次
# def before1():
#     # 判斷是否登錄,如果登錄了繼續往下走,如果沒登陸
#     print("我執行了2222")


# 2. 請求走了,會執行它,註冊多個,按照從下往上的順序執行
@app.after_request
def after(response):
    # 寫入cookie,寫入響應頭。。。處理跨域
    print(response)
    print("請求走了1111")
    return response


# @app.after_request
# def after2(response):
#     print(response)
#     print("請求走了2222")
#     return response


# 3. before_first_request 只會執行一次,以後就不執行了,跟用戶無關,做一些初始化的工作
@app.before_first_request
def first():
    print("我的第一次")


# 4. teardown_request 每一個請求之後綁定一個函數,即使遇到了異常,debug為false的情況下
@app.teardown_request
def teardown(e):
    print(e)  # 記錄日誌,錯誤日誌request.method
    print("我是teardown")


# 5. errorhandler 綁定響應狀態碼,當狀態碼一致,就會執行它
@app.errorhandler(404)
def err_404(arg):
    print(arg)
    return render_template('404.html')


@app.errorhandler(500)  # 500錯誤的返回
def err_500(arg):
    print(arg)
    return render_template('500.html')


# 6. 標籤template_global
@app.template_global()
def add(a1, a2):
    return a1 + a2


# 7. 過濾器template_filter
@app.template_filter()
def add2(a1, a2, a3):
    return a1 + a2 + a3


@app.route('/')
def index():
    # raise Exception("錯誤")

    l = [1, 2, 4]
    print(l[9])
    print("我是視圖函數")
    return "hello web"


@app.route("/home")
def home():
    return render_template('home.html')


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

2、藍圖

# blueprint
	現在項目都是單個py文件--》想劃分目錄--》自己訂製目錄結構--》app經常用---》各個文件中導來導去---》出現循環引入問題
    
# 一個項目有多個app,每個app有自己一套路由,使用藍圖來管理

# 第一步:定義藍圖對象
user = Blueprint('user', __name__)

# 第二步:使用藍圖寫路徑,寫請求擴展(只針對於當前藍圖生效)
@user.route('/index')

# 第三步:把藍圖註冊進app中
app.register_blueprint(user)



# 小型項目目錄劃分
pro_flask
	-pro_flask
		-__init__.py
	-statics
	-templates
	-views
		account.py
		user.py
		blog.py
	-run.py
    
    
 # 大型項目 --》有多個app
pro_flask 
	-pro_flask  # 包
	__init__.py  # 包的init
	admin  # 包
		__init__.py  # 包的init
		static  # 自己的靜態文件
		templates  # 自己的模板文件
		models.py
		views.py  # 自己的視圖函數
	web   # 包
		__init__.py
		static 
		templates
		views.py
  
	run.py   # 啟動文件
	
  
# 以後如何劃分,千奇百怪,但是都使用藍圖來做,藍圖管理自己的路由和請求擴展

3、g對象

# global的縮寫,為了實現在同一個請求中,傳遞數據,上下文傳遞,賦值取值只針對於當次請求生效
	

# 類比 django 中的 request對象,內有context 屬性
	django中間件中,假設想放到request中一個數據
	request.name="lqz"
	rerquest.context['name']='lqz'
	rerquest.context['method']='nb'
	到視圖函數中,就可以取出來
  
 
  
 # g和session有什麼區別?
	g只針對於當次請求
	session針對於多次請求
from flask import Flask, request, g

app = Flask(__name__)


@app.route('/')
def index():
    print("我是視圖函數")
    # request.a=1
    # request.b=2
    # 當次請求中的上下文
    g.a = 1
    g.b = 3
    print(add())
    return "hello web"


@app.route('/home')
def home():
    g.a = 3
    g.b = 5
    print(add())
    return "hello home"


def add():
    return g.a + g.b
    # return request.a+request.b


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