W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
比如說你有一個應用函數(shù)返回用戶應該跳轉(zhuǎn)到的 URL 。想象它總是會跳轉(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')
如你所見,它訪問了請求對象。當你試圖在純 Python shell 中運行這段代碼時, 你會看見這樣的異常:
>>> 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'
這有很大意義,因為我們當前并沒有可以訪問的請求。所以我們需要制造一個 請求并且綁定到當前的上下文。 test_request_context 方 法為我們創(chuàng)建一個 RequestContext:
>>> ctx = app.test_request_context('/?next=http://example.com/')
可以通過兩種方式利用這個上下文:使用 with 聲明或是調(diào)用 push() 和 pop() 方法:
>>> ctx.push()
從這點開始,你可以使用請求對象:
>>> redirect_url()
u'http://example.com/'
直到你調(diào)用 pop:
>>> ctx.pop()
因為請求上下文在內(nèi)部作為一個棧來維護,所以你可以多次壓棧出棧。這在實現(xiàn) 內(nèi)部重定向之類的東西時很方便。
更多如何從交互式 Python shell 中利用請求上下文的信息,請見 與 Shell 共舞 章節(jié)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: