8

python发送form-data数据

 3 years ago
source link: https://segmentfault.com/a/1190000040034749
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

最近在接入其他接口的时候,要发送form-data的数据,以为就是将在headers中添加一下Content-Type为multipart/form-data,可能是我太天真了,添加之后把传入的数据都整没了,很是痛苦。于是四处找资料,终于找到了以下两种方案,提供给有需要的同志们。

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]})

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK