Python requests插件
2019-12-11 本文已影响0人
李霖弢
Requests在Python内置模块的基础上进行了高度的封装
安装
pip3 install requests
请求
params
用于query string,data
用于body,files
用于文件,headers
设置请求头,timeout
设置超时,json
也用于body(且不用先调用json.dumps
)
import requests
import json
from requests.exceptions import ReadTimeout
headers= {
'content-type':'application/json;charset=utf8'
}
payload = {'k1':'v1','k2':'v2'}
files = {'file': open('report.xls', 'rb')}
try:
res = requests.post('http://httpbin.org/get',data=json.dumps(payload), params=payload, headers = headers, timeout=0.5, files=files)
res.raise_for_status()
except BaseException as e:
print("BaseException", type(e), e)
try:
if res.json()["error"]:
print(res.json()["error"])
except BaseException:
pass
else:
print(res.json()["result"])
finally:
print('request over')
res的属性
.text
Requests 会基于 HTTP 头部对响应的编码作出有根据的推测并将content解析,也可以自行指定编码方式。
每当访问.text
都将会使用 .encoding
解码
res.encoding='utf-16'
print(res.encoding)
print(res.text)
若均无指定则默认为'utf-8'
.content
自动解码 gzip 和 deflate 传输编码的响应数据,并返回bytes类型。
通常读取文件/图片时使用该属性
type(res.content) is bytes #True
str(res.content,'utf-16')
res.content.decode('utf-16')
# utf-8 / utf-16 / unicode_escape / gb2312
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(res.content))
.iter_content
用于保存文件到本地
with open(filename, 'wb') as fd:
for chunk in res.iter_content(chunk_size):
fd.write(chunk)
.json()
内置的 JSON 解码器
成功调用 .json()
并不意味着响应的成功,应使用 res.raise_for_status()
或者检查 res.status_code
。
- res.raise_for_status()
接口出错时会抛出错误信息 - res.status_code 响应状态码
通过res.status_code == requests.codes.ok
可以判断是否请求成功