Python requests not processing cookies correctly?

I have a problem with simple authorization and loading an API script.

Upon authorization, the client receives several cookies, including the PHPSESSID cookie (in the browser).

I use the requests.post method with the 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 only for custom User-Agent .

Authorization is 100% beautiful (there is a logout on the page). Later, I try to load data using allowed session cookies:

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

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

The only difference is that cookie 2 is sent by the request class, and google chrome sends 7 .

Refresh . Double flag, the first request receives 7 cookies. The post method just ignores half ...

+5
source share
1 answer

My mistake in the code was that I was assigning a cookie from each subsequent API request to the session cookie dictionary. At each request from the moment of logging in, the cookies were "reset" with ready-made answers, this was a problem. Since auth cookies are only set upon login requests, they are lost on the next request.

After each allowed request, I use update () without assigning.

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

Solves my problem, loading works fine!

+2
source

All Articles