Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python's requests do not handle cookies correctly?

I have problem with simple authorization and upload API script.

When authorized, client receives several cookies, including PHPSESSID cookie (in browser).

I use requests.post method with form data for authorization:

r = requests.post(url, headers = self.headers, data = formData)
self.cookies = requests.utils.dict_from_cookieja(r.cookies)

Headers are used for custom User-Agent only.

Authorization is 100% fine (there is a logout link on the page). Later, i try to upload data using the authorized session cookies:

r = requests.post(url, files = files, data = formData, headers = self.headers, cookies = self.cookies)

But site rejects the request. If we compare the requests from script and google chrome (using Wireshark), there is no differences in request body.

Only difference is that 2 cookies sent by requests class, while google chrome sends 7.

Update: Double checked, first request receives 7 cookies. post method just ignore half...

like image 911
Croll Avatar asked Jul 03 '15 23:07

Croll


1 Answers

My mistake in code was that i was assigning cookies from each next API request to the session cookies dictionary. On each request since logged in, cookies was 'reset' by upcoming response cookies, that's was the problem. As auth cookies are assigned only at login request, they were lost at the next request.

After each authorized request i use update(), not assigning.

self.cookies.update( requests.utils.dict_from_cookiejar(r.cookies) )

Solves my issue, upload works fine!

like image 132
Croll Avatar answered Nov 13 '22 19:11

Croll