Flask 深入上下文作用域

2021-08-10 17:58 更新

比如說你有一個(gè)應(yīng)用函數(shù)返回用戶應(yīng)該跳轉(zhuǎn)到的 URL 。想象它總是會(huì)跳轉(zhuǎn)到 URL 的 next 參數(shù),或 HTTP referrer ,或索引頁:

from flask import request, url_for

def redirect_url():
    return request.args.get('next') or \
           request.referrer or \
           url_for('index')

如你所見,它訪問了請(qǐng)求對(duì)象。當(dāng)你試圖在純 Python shell 中運(yùn)行這段代碼時(shí), 你會(huì)看見這樣的異常:

>>> redirect_url()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'request'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'request'

這有很大意義,因?yàn)槲覀儺?dāng)前并沒有可以訪問的請(qǐng)求。所以我們需要制造一個(gè) 請(qǐng)求并且綁定到當(dāng)前的上下文。 test_request_context 方 法為我們創(chuàng)建一個(gè) RequestContext:

>>> ctx = app.test_request_context('/?next=http://example.com/')

可以通過兩種方式利用這個(gè)上下文:使用 with 聲明或是調(diào)用 push() 和 pop() 方法:

>>> ctx.push()

從這點(diǎn)開始,你可以使用請(qǐng)求對(duì)象:

>>> redirect_url()
u'http://example.com/'

直到你調(diào)用 pop:

>>> ctx.pop()

因?yàn)檎?qǐng)求上下文在內(nèi)部作為一個(gè)棧來維護(hù),所以你可以多次壓棧出棧。這在實(shí)現(xiàn) 內(nèi)部重定向之類的東西時(shí)很方便。

更多如何從交互式 Python shell 中利用請(qǐng)求上下文的信息,請(qǐng)見 與 Shell 共舞 章節(jié)。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)