Flask 偽造資源和上下文

2021-08-10 17:39 更新

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)


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)