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

上一篇 下一篇

猜你喜欢

热点阅读