Recently, when connecting to other interfaces, I need to send form-data data. I thought I would add the Content-Type to multipart/form-data in the headers. Maybe I was too naive. After adding it, I will add all the incoming data. It's gone, it's very painful. So I looked around for information, and finally found the following two plans, which were provided to comrades in need.

requests

  • requests_toolbelt

    from requests_toolbelt import MultipartEncoder
    import requests
    
    m = MultipartEncoder(
      fields={'field0': 'value',
             'field1': 'value',
              'field2': ('文件名称', open('文件地址/file.py', 'rb'), 'text/plain')}
      )

r = requests.post('http://httpbin.org/post',

              data=m,
              headers={'Content-Type': m.content_type})

### urlib3
- encode_multipart_formdata

from urlib3 import encode_multipart_formdata
import requests

m = encode_multipart_formdata()

r = requests.post('http://httpbin.org/post',

              data=m[0],
              headers={'Content-Type': m[1]})

二十一
1.4k 声望867 粉丝

无论遇到多大的困难,你总是能扛过去,坚持一件事,对自己