How to send a “multipart/form-data” with requests in python?

前端 未结 9 1792
野趣味
野趣味 2020-11-22 01:29

How to send a multipart/form-data with requests in python? How to send a file, I understand, but how to send the form data by this method can not understand.

9条回答
  •  粉色の甜心
    2020-11-22 02:02

    To clarify examples given above,

    "You need to use the files parameter to send a multipart form POST request even when you do not need to upload any files."

    files={}

    won't work, unfortunately.

    You will need to put some dummy values in, e.g.

    files={"foo": "bar"}
    

    I came up against this when trying to upload files to Bitbucket's REST API and had to write this abomination to avoid the dreaded "Unsupported Media Type" error:

    url = "https://my-bitbucket.com/rest/api/latest/projects/FOO/repos/bar/browse/foobar.txt"
    payload = {'branch': 'master', 
               'content': 'text that will appear in my file',
               'message': 'uploading directly from python'}
    files = {"foo": "bar"}
    response = requests.put(url, data=payload, files=files)
    

    :O=

提交回复
热议问题