Accessing all cookies in the Flask test response


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("/")
'mycookie=value; Expires=Thu, 27-Jun-2019 13:42:19 GMT; Max-Age=1800; Path=/'

for item in response.headers:

('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;; Expires=Sun, 04-Apr-2021 13:42:19 GMT; Max-Age=62208000; Path=/')
('Set-Cookie', 'mycookie3=something;; 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?


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


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”:"/login")
cookie = next(
    (cookie for cookie in client.cookie_jar if == "user_id"),
assert cookie is not None
assert cookie.value == "4"

Answered By – davidism

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published