user1592380
user1592380

Reputation: 36267

Trying to load cookie into requests session from dictionary

I'm working with the python requests library. I am trying to load a requests session with a cookie from a dictionary:

cookie = {'name':'my_cookie','value': 'kdfhgfkj' ,'domain':'.ZZZ.org', 'expires':'Fri, 01-Jan-2020 00:00:00 GMT'}

I've tried:

s.cookies.set_cookie(cookie)

but this gives:

File "....lib\site-packages\requests\cookies.py", line 298, in set_cookie
    if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
AttributeError: 'dict' object has no attribute 'value'

What am I doing wrong?

Upvotes: 5

Views: 11344

Answers (2)

crifan
crifan

Reputation: 14328

session.cookies.set_cookie's parameter should be Cookie object, NOT dict (of cookie)

if you want add new cookie into session.cookies from dict, you can use:

or

more detail pls refer to my another post's answer

Upvotes: 0

alecxe
alecxe

Reputation: 473893

cookies has a dictionary-like interface, you can use update():

s.cookies.update(cookie)

Or, just add cookies to the next request:

session.get(url, cookies=cookie)

It would "merge" the request cookies with session cookies and the newly added cookies would be retained for subsequent requests, see also:

Upvotes: 12

Related Questions