W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
0.10 新版功能.
在應(yīng)用上下文或 flask.g 對(duì)象上存儲(chǔ)用戶認(rèn)證信息和數(shù)據(jù)庫(kù)連接 非常常見。一般的模式是在第一次使用對(duì)象時(shí),把對(duì)象放在應(yīng)用上下文或 flask.g 上面,而在請(qǐng)求銷毀時(shí)移除對(duì)象。試想一下例如下面的獲 取當(dāng)前用戶的代碼:
def get_user():
user = getattr(g, 'user', None)
if user is None:
user = fetch_current_user_from_database()
g.user = user
return user
對(duì)于測(cè)試,這樣易于從外部覆蓋這個(gè)用戶,而不用修改代碼。連接 flask.appcontext_pushed 信號(hào)可以很容易地完成這個(gè)任務(wù):
from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
并且之后使用它:
from flask import json, jsonify
@app.route('/users/me')
def users_me():
return jsonify(username=g.user.username)
with user_set(app, my_user):
with app.test_client() as c:
resp = c.get('/users/me')
data = json.loads(resp.data)
self.assert_equal(data['username'], my_user.username)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: