Python Requests: Post JSON and file in single request

前端 未结 6 519
天涯浪人
天涯浪人 2020-12-01 05:16

I need to do a API call to upload a file along with a JSON string with details about the file.

I am trying to use the python requests lib to do this:



        
6条回答
  •  我在风中等你
    2020-12-01 05:40

    See this thread How to send JSON as part of multipart POST-request

    Do not set the Content-type header yourself, leave that to pyrequests to generate

    def send_request():
        payload = {"param_1": "value_1", "param_2": "value_2"}
        files = {
            'json': (None, json.dumps(payload), 'application/json'),
            'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')
        }
    
        r = requests.post(url, files=files)
        print(r.content)
    

提交回复
热议问题