dat*_*bed 10 python werkzeug flask
在使用 Flask 测试客户端发出请求后,我想访问服务器设置的 cookie。如果我迭代response.headers,我会看到多个Set-Cookie标题,但如果我这样做response.headers["Set-Cookie"],我只会得到一个值。此外,标头是难以测试的未解析字符串。
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=/')
Run Code Online (Sandbox Code Playgroud)
为什么访问Set-Cookie标题只给我一个标题?如何访问 cookie 及其属性以进行测试?
dav*_*ism 15
response.headers是 a MultiDict,它提供了getlist获取给定键的所有值的方法。
response.headers.getlist('Set-Cookie')
Run Code Online (Sandbox Code Playgroud)
检查客户端拥有的 cookie 可能更有用,而不是Set-Cookie由响应返回的特定原始标头。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"
Run Code Online (Sandbox Code Playgroud)