Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 877
user1592380 Avatar asked Aug 10 '15 20:08

user1592380


People also ask

How do I add cookies to my requests?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

How do you get session cookies in Python?

How do I get cookie data in python? Use the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies.

How do I update session cookies?

On your Android device, open the Chrome app. At the top right, tap More More and then Settings. Tap Site settings and then Cookies. Next to “Cookies,” switch the setting on.


1 Answers

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:

  • Update Cookies in Session Using python-requests Module
like image 61
alecxe Avatar answered Nov 15 '22 02:11

alecxe