How to send cookies in a post request with the Python Requests library? How to send cookies in a post request with the Python Requests library? python python

How to send cookies in a post request with the Python Requests library?


The latest release of Requests will build CookieJars for you from simple dictionaries.

import requestscookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)


Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:

import requestsr1 = requests.post('http://www.yourapp.com/login')r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)


If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:

import requests...def application(environ, start_response):    cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}    response_headers = [('Content-type', 'text/plain')]    response_headers.append(('Set-Cookie',cookie))...    return [bytes(post_env),response_headers]

I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.