2017-09-26 77 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) 

希望它有幫助。

相關問題