在我用 Flask 测试客户端发出请求后,我想访问服务器设置的 cookie。如果我遍历 response.headers
,我会看到多个 Set-Cookie
header ,但如果我执行 response.headers["Set-Cookie"]
,我只得到一个值。此外, header 是难以测试的未解析字符串。
response = client.get("/")
print(response.headers['Set-Cookie'])
'mycookie=value; Expires=Thu, 27-Jun-2019 13:42:19 GMT; Max-Age=1800; Path=/'
for item in response.headers:
print(item)
('Content-Type', 'application/javascript')
('Content-Length', '215')
('Set-Cookie', 'mycookie=value; Expires=Thu, 27-Jun-2019 13:42:19 GMT; Max-Age=1800; Path=/')
('Set-Cookie', 'mycookie2=another; Domain=.client.com; Expires=Sun, 04-Apr-2021 13:42:19 GMT; Max-Age=62208000; Path=/')
('Set-Cookie', 'mycookie3=something; Domain=.client.com; Expires=Thu, 04-Apr-2019 14:12:19 GMT; Max-Age=1800; Path=/')
为什么访问 Set-Cookie
header 只给我一个 header ?我如何访问 cookie 及其属性以进行测试?
最佳答案
response.headers
是一个 MultiDict
,它提供了 getlist
获取给定键的所有值的方法。
response.headers.getlist('Set-Cookie')
检查客户端拥有的 cookie 比响应返回的特定原始 Set-Cookie
header 可能更有用。 client.cookie_jar
是一个 CookieJar
例如,迭代它会产生 Cookie
实例。例如,获取名为“user_id”的 cookie 的值:
client.post("/login")
cookie = next(
(cookie for cookie in client.cookie_jar if cookie.name == "user_id"),
None
)
assert cookie is not None
assert cookie.value == "4"
关于python - 访问 Flask 测试响应中的所有 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55517607/