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

前端 未结 9 1738
野趣味
野趣味 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:00

    Here is the simple code snippet to upload a single file with additional parameters using requests:

    url = 'https://<file_upload_url>'
    fp = '/Users/jainik/Desktop/data.csv'
    
    files = {'file': open(fp, 'rb')}
    payload = {'file_id': '1234'}
    
    response = requests.put(url, files=files, data=payload, verify=False)
    

    Please note that you don't need to explicitly specify any content type.

    NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.

    0 讨论(0)
  • 2020-11-22 02:02

    I'm trying to send a request to URL_server with request module in python 3. This works for me:

    # -*- coding: utf-8 *-*
    import json, requests
    
    URL_SERVER_TO_POST_DATA = "URL_to_send_POST_request"
    HEADERS = {"Content-Type" : "multipart/form-data;"}
    
    def getPointsCC_Function():
      file_data = {
          'var1': (None, "valueOfYourVariable_1"),
          'var2': (None, "valueOfYourVariable_2")
      }
    
      try:
        resElastic = requests.post(URL_GET_BALANCE, files=file_data)
        res = resElastic.json()
      except Exception as e:
        print(e)
    
      print (json.dumps(res, indent=4, sort_keys=True))
    
    getPointsCC_Function()
    

    Where:

    • URL_SERVER_TO_POST_DATA = Server where we going to send data
    • HEADERS = Headers sended
    • file_data = Params sended
    0 讨论(0)
  • 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=

    0 讨论(0)
提交回复
热议问题