requests.post和requests.session.post方法的区别
1. requests.post()
调用形式:requests.post(url, data={key: value}, json={key: value}, args)
args
表示还有很多可选参数,例如:
1.1 file : 一个文件字典列表
myfiles = {'file': open('myfirstreact.png' ,'rb')}
x = requests.post(url, files = myfiles)
表示向目标链接post一个图片('rb'表示以二进制格式读取文件)
1.2 allow_redirects : 表示是否允许网页重定向
默认为True
1.3 cookies : 一个字典格式的cookies
myobj = {'somekey': 'somevalue'}
x = requests.post(url, data = myobj, cookies = {"favcolor": "Red"}) #根据目标url的cookies
1.4 headers : 请求头
x = requests.post(url,data={},headers = {
'header_one':'content',
'header_two':'content',
...
})
1.5 timeout : 等待服务器响应的时间
默认为None
,表示一直等待直到服务器响应。
也可以自定义,如果超出时间表示“在这一次请求中响应超时”。
x = requests.post(url, data = myobj, timeout=0.001)#表示等待0.001秒
1.5 data和json的区别
根据不同的url的http请求,需要发送对应的数据,比如有的网站是直接以字典格式发送数据,而有的可能是在前端打包成json格式在发送请求。
具体需要看请求头中的content-type
参数:如果请求头中content-type
为application/json
, 为json形式,post请求使用json参数。
如果为application/x-www-form-urlencoded
,为表单形式,post请求时使用使用data参数。
reference_1
2. requests.session.post()
The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see <HTTP persistent connection).
-- reference_2
这段话也就表明,session中的post方法可以维持一个实例中的某些参数,保持会话连接,让你在实例中保存cookies。
其余的参数和requests.post()相同。
而且从reference_3中对源码的分析中也可以看出,requests.post()在调用完成之后,连接池就会被关闭;而requests.session.post()会将链接保存,将cookies保存在同一个实例中。
#官方参考中的示例代码
s = requests.Session()
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
表明在r这一个实例中,两次对不同链接的请求的cookies是相同的。