该方式适用于请求类型 multipart/form-data。
具体表现是请求头(header)中
- Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryaPJUIAvGfcSPVJIJ
- pip install requests-toolbelt
- from requests_toolbelt import MultipartEncoder
- import requests
# text/plain 需要根据实际情况替换,可能是:'image/png'
# fields 里参数个数是根据实际来定义的,几个文件就定义几个field ,具体的名字要根据实际情况调整
# fields 里参数个数是根据实际来定义的,几个文件就定义几个field ,具体的名字要根据实际情况调整
- 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})
- # 当然 header 可以在自己定义好的header里加入'Content-Type': m.content_type