Update Cookies in Session Using python-requests Module

☆樱花仙子☆ 提交于 2019-12-01 19:10:23
Thomas Orozco

requests can do that for you, provided you tell it all the requests you make are part of the same session:

>>> import requests
>>> s = requests.session()
>>> s.get('https://www.google.com')
<Response [200]>
>>> s.cookies
<<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='NID'...

Subsequent requests made using s.get or s.post will re-use and update the cookies the server sent back to the client.


To add a Cookie on your own to a single request, you would simply add it via the cookies parameter.

>>> s.get('https://www.google.com', cookies = {'cookieKey':'cookieValue'})

Unless the server sends back a new value for the provided cookie, the session will not retain the provided cookie.

This code worked for me. hope it can help to someone else.

I want to update session.cookies variable with received response values from post request. so, same request value can be used in another post/get request.

here, what I did:

1) updated requests module to 1.0.3 version.

2) created 2 functions

   session = requests.session() 
   def set_SC(cookie_val):
            for k,v in cookie_dict.iteritems():
                if not isinstance(v, str):
                    cookie_dict[k] =  str(v) 
            requests.utils.add_dict_to_cookiejar(session.cookies,
                                                 cookie_val)

    def get_SC():
            return requests.utils.dict_from_cookiejar(session.cookies)

    In another function:
    setSC(response.content)

In order to provide a cookie yourself to the requests module you can use the cookies parameter for a single request and give it a cookie jar or dict like object containing the cookie(s).

>>> import requests
>>> requests.get('https://www.example.com', cookies {'cookieKey':'cookieValue'})

But if you want to retain the provided cookie without having to set the cookies parameter everytime, you can use a reqests session which you can also pass to other funtions so they can use and update the same cookies:

>>> session = requests.session()
>>> session.cookies.set('cookieKey', 'cookieName')
# In order to avoid cookie collisions
# and to only send cookies to the domain / path they belong to
# you have to provide these detail via additional parameters
>>> session.cookies.set('cookieKey', 'cookieName', path='/', domain='www.example.com')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!