【发布时间】:2017-08-23 14:25:17
【问题描述】:
我知道可以使用 session_transaction() 方法创建会话对象。但是,有没有办法访问例如“/”路由被命中时创建的当前会话对象?我做了from flask import session 来访问会话,但它是空的。让我知道是否可能。谢谢。
【问题讨论】:
我知道可以使用 session_transaction() 方法创建会话对象。但是,有没有办法访问例如“/”路由被命中时创建的当前会话对象?我做了from flask import session 来访问会话,但它是空的。让我知道是否可能。谢谢。
【问题讨论】:
This 是您正在寻找的。然而,正如它所说,您必须使用您在 with 语句中创建的实例化。
with app.test_client() as c:
with c.session_transaction() as sess:
sess['a_key'] = 'a value'
# once this is reached the session was stored
result = app.test_client.get('/a_url')
# NOT part of the 2nd context
请注意,如果您在 with c.session_transaction() as sess 语句的范围内运行测试,这将不起作用,它需要在该块之后运行。
【讨论】:
session对象所做的修改只写了事务关闭时返回实际客户端的会话。
如果您想从测试中读取写入视图中的会话数据,一种方法是将会话视图模拟为 dict 并在测试中验证会话。这是一个使用Python's unittest.mock的例子:
app.py
from flask import Flask, session, request
app = Flask(__name__)
app.config["SECRET_KEY"] = "my secret key"
@app.route("/", methods=["POST"])
def index():
session["username"] = request.form["username"]
return "Username saved in session"
test_index.py
from unittest.mock import patch
from app import app
def test_index():
with patch("app.session", dict()) as session:
client = app.test_client()
response = client.post("/", data={
"username": "test"
})
assert session.get("username") == "test"
assert response.data == b"Username saved in session"
当然,您可以使用任何您喜欢的模拟解决方案。
【讨论】:
with 块中更改 session 时,请确保不要创建新的字典(例如,session = {}),因为这会破坏补丁。我在调试过程中浪费了很多时间,所以希望我能帮别人省一些痛苦。