2017-09-26 90 views
0

我正在使用Python 3.6.2中的HTTP.client与API进行通信。如何使用Python http.client PUT方法上传二进制/视频文件?

为了上传文件,它需要三个阶段的过程。

我已成功地使用POST方法进行通话,并且服务器按照我的预期返回数据。

但是,需要上传实际文件的阶段是PUT方法 - 我无法弄清楚如何语法代码以包含指向存储器上实际文件的指针 - 该文件是mp4视频文件。 这里是代码的我的小白注解:)

#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() 

我在这个阶段找回的响应是一个 片段“错误400错误的请求 - 无法获取文件信息。”

我确定这涉及到body =“C:\ Test.mp4”部分的代码。

你能告诉我如何正确引用PUT方法中的文件吗?

在此先感谢

回答

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

将会把实际字符串"C:\Test.mp4"在您的要求,命名"C:\Test.mp4"像您期望的文件不是内容的主体。

您需要打开文件,读取它的内容,然后将其作为主体传递。或者流式传输,但AFAIK http.client不支持,因为你的文件似乎是一个视频,它可能是巨大的,并会使用大量的RAM没有很好的理由。

我的建议是使用requests,这是一种更好的方式LIB做这样的事情:

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()) 
+0

Ledge。像魅力一样工作,谢谢! – yekootmada

0

我不知道这是否是对你有用,但你可以尝试发送POST请求与请求模块:

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) 

希望它有帮助。

相关问题