Accessing all cookies in the Flask test response

旧街凉风 提交于 2020-07-06 11:06:27

问题


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=/')

Why does accessing the Set-Cookie header only give me one header? How can I access the cookies and their properties for testing?


回答1:


response.headers is a MultiDict, which provides the getlist method to get all the values for a given key.

response.headers.getlist('Set-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"


来源:https://stackoverflow.com/questions/55517607/accessing-all-cookies-in-the-flask-test-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!