How to upload a binary/video file using Python http.client PUT method?

删除回忆录丶 提交于 2020-06-28 05:56:12

问题


I am communicating with an API using HTTP.client in Python 3.6.2.

In order to upload a file it requires a three stage process.

I have managed to talk successfully using POST methods and the server returns data as I expect.

However, the stage that requires the actual file to be uploaded is a PUT method - and I cannot figure out how to syntax the code to include a pointer to the actual file on my storage - the file is an mp4 video file. Here is a snippet of the code with my noob annotations :)

#define connection as HTTPS and define URL
uploadstep2 = http.client.HTTPSConnection("grabyo-prod.s3-accelerate.amazonaws.com")

#define headers
headers = {
    'accept': "application/json",
    'content-type': "application/x-www-form-urlencoded"
}

#define the structure of the request and send it.
#Here it is a PUT request to the unique URL as defined above with the correct file and headers.
uploadstep2.request("PUT", myUniqueUploadUrl, body="C:\Test.mp4", headers=headers)

#get the response from the server
uploadstep2response = uploadstep2.getresponse()

#read the data from the response and put to a usable variable
step2responsedata = uploadstep2response.read()

The response I am getting back at this stage is an "Error 400 Bad Request - Could not obtain the file information."

I am certain this relates to the body="C:\Test.mp4" section of the code.

Can you please advise how I can correctly reference a file within the PUT method?

Thanks in advance


回答1:


uploadstep2.request("PUT", myUniqueUploadUrl, body="C:\Test.mp4", headers=headers)

will put the actual string "C:\Test.mp4" in the body of your request, not the content of the file named "C:\Test.mp4" as you expect.

You need to open the file, read it's content then pass it as body. Or to stream it, but AFAIK http.client does not support that, and since your file seems to be a video, it is potentially huge and will use plenty of RAM for no good reason.

My suggestion would be to use requests, which is a way better lib to do this kind of things:

import requests
with open(r'C:\Test.mp4'), 'rb') as finput:
   response = requests.put('https://grabyo-prod.s3-accelerate.amazonaws.com/youruploadpath', data=finput)
   print(response.json())



回答2:


I do not know if it is useful for you, but you can try to send a POST request with requests module :

import requests
url = ""
data = {'title':'metadata','timeDuration':120}
mp3_f = open('/path/your_file.mp3', 'rb')
files = {'messageFile': mp3_f}

req = requests.post(url, files=files, json=data)
print (req.status_code)
print (req.content)

Hope it helps .



来源:https://stackoverflow.com/questions/46429551/how-to-upload-a-binary-video-file-using-python-http-client-put-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!