Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using requests module, how to handle 'set-cookie' in request response?

Tags:

I'm attempting to open a login page (GET), fetch the cookies provided by the webserver, then submit a username and password pair to log into the site (POST).

Looking at this Stackoverflow question/answer, I would think that I would just do the following:

import requests import cookielib   URL1 = 'login prompt page' URL2 = 'login submission URL' jar = cookielib.CookieJar()  r = requests.get(URL1, cookies=jar) r2 = requests.post(URL2, cookies=jar, data="username and password data payload") 

However, in r there is a set-cookie in the header, but that isn't changing in the jar object. In fact, nothing is being populated into jar as the linked question's response would indicate.

I'm getting around this in my code by having a headers dict and after doing the GET or POST, using this to handle the set-cookie header:

headers['Cookie'] = r.headers['set-cookie'] 

Then passing around the header in the requests methods. Is this correct, or is there a better way to apply the set-cookie?

like image 898
tommy_o Avatar asked Feb 12 '14 18:02

tommy_o


People also ask

How do you pass cookies in request?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.

How do you get a response cookie 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 does request module work?

The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).


2 Answers

Ignore the cookie-jar, let requests handle cookies for you. Use a session object instead, it'll persist cookies and send them back to the server:

with requests.Session() as s:     r = s.get(URL1)     r = s.post(URL2, data="username and password data payload") 
like image 56
Martijn Pieters Avatar answered Sep 24 '22 20:09

Martijn Pieters


There's an included class called a session which automatically handles this sort of thing for you. You can create an instance of it, and then call get and set right on that instance instead.

import requests  URL1 = 'login prompt page' URL2 = 'login submission URL'  session = requests.Session()  r = session.get(URL1) r2 = session.post(URL2, data="username and password data payload") 
like image 40
TankorSmash Avatar answered Sep 26 '22 20:09

TankorSmash