2017-09-26 1 views
0

파이썬 3.6.2에서 HTTP.client를 사용하여 API와 통신 중이다.파이썬을 사용하여 바이너리/비디오 파일을 업로드하는 방법 http.client PUT 메소드?

파일을 업로드하려면 3 단계 프로세스가 필요합니다.

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 충분한 이유없이 사용합니다.

나의 제안은 사물의 종류 할 수있는 방법 더 나은 lib 디렉토리입니다 requests을 사용하는 것입니다 :

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

선반. 매력처럼 작동했습니다, 감사합니다! – 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) 

희망이 있습니다.

관련 문제