How to add a cookie to the cookiejar in python requests library

fat fantasma picture fat fantasma · Jun 20, 2013 · Viewed 59k times · Source

I am trying to add a cookie to an existing cookiejar using the python requests 1.2.3 library. Every time I add the new cookie, the data in the jar is munged for the new cookie. Keys missing, Values missing or matched to incorrect Keys. I'm not sure if it's a Request library bug or I'm not sending the cookie correctly. I'm using the following code that is resulting in a bad cookie in cookiejar. Am I formatting the cookie correctly? Any ideas?

    my_cookie = {
           'domain':'www.mydomain.com',
           'expires':None,
           'name':'COOKIE_NAME',
           'path':'/',
           'value':'the cookie works',
           'version':0
}

s = requests.Session()
requests.utils.add_dict_to_cookiejar(s.cookies, my_cookie)

Answer

Kamel picture Kamel · Aug 18, 2018

Quick Answer

import requests
s = requests.session()
# Note that domain keyword parameter is the only optional parameter here
cookie_obj = requests.cookies.create_cookie(domain='www.domain.com',name='COOKIE_NAME',value='the cookie works')
s.cookies.set_cookie(cookie_obj)

Detailed Answer

I do not know if this technique was valid when the original question was asked, but ideally you would generate your own cookie object using **requests.cookies.create_cookie(name,value,kwargs) and then add it to the cookie jar via **requests.cookies.RequestsCookieJar.set_cookie(cookie,*args,kwargs). See the source/documentation here.

Adding a custom cookie to requests session

>>> import requests
>>> s = requests.session()
>>> print(s.cookies)
<RequestsCookieJar[]>
>>> required_args = {
        'name':'COOKIE_NAME',
        'value':'the cookie works'
    }
>>> optional_args = {
    'version':0,
    'port':None,
#NOTE: If domain is a blank string or not supplied this creates a
# "super cookie" that is supplied to all domains.
    'domain':'www.domain.com',
    'path':'/',
    'secure':False,
    'expires':None,
    'discard':True,
    'comment':None,
    'comment_url':None,
    'rest':{'HttpOnly': None},
    'rfc2109':False
}
>>> my_cookie = requests.cookies.create_cookie(**required_args,**optional_args)
# Counter-intuitively, set_cookie _adds_ the cookie to your session object,
#  keeping existing cookies in place
>>> s.cookies.set_cookie(my_cookie)
>>> s.cookies
<RequestsCookieJar[Cookie(version=0, name='COOKIE_NAME', value='the cookie works', port=None, port_specified=False, domain='www.domain.com', domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>

Bonus: Lets add a super cookie then delete it

>>> my_super_cookie = requests.cookies.create_cookie('super','cookie')
>>> s.cookies.set_cookie(my_super_cookie)
# Note we have both our previous cookie and our new cookie
>>> s.cookies
<RequestsCookieJar[Cookie(version=0, name='super', value='cookie', port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False), Cookie(version=0, name='COOKIE_NAME', value='the cookie works', port=None, port_specified=False, domain='www.domain.com', domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
# Deleting is simple, note that this deletes the cookie based on the name,
# if you have multiple cookies with the same name it will raise
# requests.cookies.CookieConflictError
>>> del s.cookies['super']
>>> s.cookies
<RequestsCookieJar[Cookie(version=0, name='COOKIE_NAME', value='the cookie works', port=None, port_specified=False, domain='www.domain.com', domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>