Requests 简明教程

Requests - Handling Sessions

若要在请求之间维护数据,则需要会话。因此,如果反复调用同一主机,您可以重用 TCP 连接,这反过来将提高性能。现在,让我们看看如何使用会话在发出的请求之间维护 Cookie。

To maintain the data between requests you need sessions. So, if the same host is called again and again, you can reuse the TCP connection which in turn will improve the performance. Let us now see, how to maintain cookies across requests made using sessions.

Adding cookies using session

import requests
req = requests.Session()
cookies = dict(test='test123')
getdata = req.get('https://httpbin.org/cookies',cookies=cookies)
print(getdata.text)

Output

E:\prequests>python makeRequest.py
{
   "cookies": {
      "test": "test123"
   }
}

使用会话,您可以在请求中保留 cookie 数据。还可以使用会话传递标头数据,如下所示 −

Using session, you can preserve the cookies data across requests. It is also possible to pass headers data using the session as shown below −

Example

import requests
req = requests.Session()
req.headers.update({'x-user1': 'ABC'})
headers = {'x-user2': 'XYZ'}
getdata = req.get('https://httpbin.org/headers', headers=headers)
print(getdata.headers)