文件上传
文件上传的接口请求头中的Content-Type属性就要使用multipart/form-data;
multipart/form-data是指定传输数据为二进制类型,比如图片、mp3、文件。
就可以使用一个requests_toolbelt的工具包来把文件转成二进制结构;
requests-toolbelt官方文档
安装:pip install requests-toolbelt
官网关于requests-toolbelt的例子:
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(
fields={
'field0': 'value',#第一个参数
'field1': 'value',#第二个参数
'field2': ('filename', open('file.py', 'rb'), 'text/plain')#第三个参数是文件
}
)
r = requests.post('http://httpbin.org/post', data=m,
headers={'Content-Type': m.content_type})
实战:
文件上传的fiddler接口抓包的信息与requests_toolbelt 与MultipartEncoder中参数的对应;
其中的参数boundary是分割符,是随机生成的字符串,用来分隔文本的开始和结束,会展示在Content-Type中;
Content-Type: multipart/form-data; boundary=${bound}
文件导出
例子:
response = requests.post(url=url, headers=headers, json=body,verify=False, stream=True)
content_disposition = response.headers.get('content-disposition')#截取content-disposition的filename
filename_code = content_disposition.split("=")[-1] #分隔字符串,提取文件名
import urllib
filename = urllib.parse.unquote(filename_code) #url解码
filepath = os.path.join('C:/Users/Administrator/Desktop', filename)#拼接路径
if response.status_code == 200:
if response.text: # 判断文件内容是否为空
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=1): # iter_content循环读取信息写入,chunk_size设置文件大小
f.write(chunk)
else:
print("文件为空")
注意事项:
- requests的参数stream要配置成True,以用于大文件的下载;可参考
- 文件导出接口的响应头中的content-disposition中会返回文件名的信息,可以提取出来;但是filename是通过url加密过的,需要解密;
- 需要写文件路径,不然会直接保存在python运行文件的文件夹下;
更多推荐