Cookie is not unfamiliar. Like session, it can keep state before and after http request. The difference from session is that cookie data is only stored on the client. Requests also provides corresponding methods to process cookies.
In the python requests module-session, we know that the session object in requests can keep cookies between requests, which greatly facilitates us to use cookies. When we want to set the request in the method level, we can do as the following example.
import requests
s = requests.session()
# Step 1: Send a request to set cookies in the request
cookies =dict(cookies_are='cookie1')
# tips: http://httpbin.org can be used to test http requests and responses
r1 = s.get(url='http://httpbin.org/cookies', cookies=cookies)print(r1.text)
# Step 2: Send a request to set the cookies in the request again
cookies =dict(cookies_are='cookie2')
r2 = s.get(url='http://httpbin.org/cookies', cookies=cookies)print(r2.text)
operation result
# r1.text
{" cookies":{"cookies_are":"cookie1"}}
# t2.text
{" cookies":{"cookies_are":"cookie2"}}
It can be seen from the results that this method allows cookies to only act on a single request, because method-level parameters will not be maintained across requests. This is the mechanism of the session object in requests, so I won’t repeat it here. So, what if we want to keep cookies across requests? The cross-request mechanism of the session object can still be applied here, as follows:
import requests
s = requests.session()
s.cookies.update({'cookies_are':'cookie'})
r = s.get(url='http://httpbin.org/cookies')print(r.text)
It is worth mentioning that in addition to directly using a dictionary to assign cookies, requests also provides a RequestsCookieJar object for us to use. Its behavior is similar to a dictionary, but the interface is more complete and suitable for cross-domain and cross-path use. Take a look at an example in the official documentation.
import requests
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie','yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie','blech', domain='httpbin.org', path='/elsewhere')
url ='http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)print(r.text)
operation result
{" cookies":{"tasty_cookie":"yum"}}
From the results, we can see that we use the RequestsCookieJar object to achieve the effect of sending different cookies according to different request paths, which further increases the flexibility of operating cookies.
Reference documents
https://github.com/psf/requests/blob/master/requests/cookies.py
https://requests.readthedocs.io/en/master/user/quickstart/#cookies
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts