访问Flask测试响应中的所有cookie [英] Accessing all cookies in the Flask test response
问题描述
我向Flask测试客户端提出请求后,我想访问服务器设置的cookie.如果我遍历 response.headers
,我会看到多个 Set-Cookie
标头,但是如果我这样做 response.headers ["Set-Cookie"]
,我只会得到一个价值.此外,标头是难以测试的未分析的字符串.
After I make a request with the Flask test client, I want to access the cookies that the server set. If I iterate over response.headers
, I see multiple Set-Cookie
headers, but if I do response.headers["Set-Cookie"]
, I only get one value. Additionally, the headers are unparsed strings that are hard to test.
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
标头只给我一个标头?如何访问Cookie及其属性进行测试?
Why does accessing the Set-Cookie
header only give me one header? How can I access the cookies and their properties for testing?
推荐答案
response.headers
是 getlist
方法可获取给定键的所有值.
response.headers
is a MultiDict
, which provides the getlist
method to get all the values for a given key.
response.headers.getlist('Set-Cookie')
检查客户端拥有的cookie可能比响应返回的特定原始 Set-Cookie
标头更有用. client.cookie_jar
是 CookieJar
实例,对其进行迭代将产生 Cookie
实例.例如,要获取名称为"user_id"的cookie的值:
It might be more useful to examine the cookies the client has, rather than the specific raw Set-Cookie
headers returned by a response. client.cookie_jar
is a CookieJar
instance, iterating over it yields Cookie
instances. For example, to get the value of the cookie with the name "user_id":
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"
这篇关于访问Flask测试响应中的所有cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!