The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping

--

Chapters
00:00 How To Send Cookies In A Post Request With The Python Requests Library?
00:41 Accepted Answer Score 361
00:59 Answer 2 Score 160
01:23 Answer 3 Score 1
02:08 Answer 4 Score 1
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/7164...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #cookies #httprequest #pythonrequests

#avk47



ACCEPTED ANSWER

Score 363


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

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)




ANSWER 2

Score 163


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 requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)



ANSWER 3

Score 1


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.




ANSWER 4

Score 1


The best practice of sending a request alongside with a cookie would be using the Session object. So that you would not need to parse the cookie every time for a requests.

As an example:

import requests

cookie = dict(user_session="xxx-xxx-xxx")

with requests.Session() as s:
    s.cookies.update(cookie)
    response = s.post("https:xxx.com")