티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to upload file with python requests?

requests로 파일을 업로드하는 방법

 문제 내용 

I'm performing a simple task of uploading a file using Python requests library. I searched Stack Overflow and no one seemed to have the same problem, namely, that the file is not received by the server:

나는 파이썬 requests 라이브러리를 사용하여 파일을 업로드하는 간단한 작업을 수행하고 있다. 스택 오버플로를 검색했는데 아무도 동일한 문제가 없는 것 같았습니다. 즉, 파일이 서버에 의해 수신되지 않는다는 것입니다.
import requests
url='http://nesssi.cacr.caltech.edu/cgi-bin/getmulticonedb_release2.cgi/post'
files={'files': open('file.txt','rb')}
values={'upload_file' : 'file.txt' , 'DB':'photcat' , 'OUT':'csv' , 'SHORT':'short'}
r=requests.post(url,files=files,data=values)

 

I'm filling the value of 'upload_file' keyword with my filename, because if I leave it blank, it says

'upload_file' 키워드 값을 내 파일 이름으로 채우고 있습니다. 공백으로 두면 다음과 같이 표시되기 때문입니다.
Error - You must select a file to upload!

 

And now I get

그리고 저는 아래 결과를 얻어요
File  file.txt  of size    bytes is  uploaded successfully!
Query service results:  There were 0 lines.

 

Which comes up only if the file is empty. So I'm stuck as to how to send my file successfully. I know that the file works because if I go to this website and manually fill in the form it returns a nice list of matched objects, which is what I'm after. I'd really appreciate all hints.

파일이 비어 있는 경우에만 표시됩니다. 그래서 나는 내 파일을 성공적으로 보내는 방법에 대해 고민하고 있다. 내가 이 웹사이트에 가서 수동으로 양식을 작성하면 일치하는 개체의 멋진 목록이 반환되기 때문에 파일이 작동한다는 것을 알고 있다. 모든 힌트를 주시면 정말 감사하겠습니다.

 

Some other threads related (but not answering my problem):

관련된 일부 다른 스레드(내 문제에 응답하지 않음):

 

 

 

 

 높은 점수를 받은 Solution 

If upload_file is meant to be the file, use:

upload_file이 파일인 경우 다음을 사용합니다.
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

 

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

그리고 requests는 file.txt 파일의 내용으로 설정된 upload_file 필드와 함께 여러 부분으로 구성된 POST 본문을 보냅니다.

 

The filename will be included in the mime header for the specific field:

파일 이름은 특정 필드의 MIME 헤더에 포함됩니다.
>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

 

Note the filename="file.txt" parameter.

filename="file.txt" 매개 변수를 확인합니다.

 

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

더 많은 제어가 필요한 경우 2-4개의 요소로 파일 매핑 값에 튜플을 사용할 수 있습니다. 첫 번째 요소는 파일 이름, 그 다음에 내용, 선택적 컨텐츠 유형 헤더 값 및 추가 헤더의 선택적 매핑입니다.
files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

 

This sets an alternative filename and content type, leaving out the optional headers.

선택적 헤더를 제외한 대체 파일 이름 및 내용 유형을 설정합니다.

 

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

다른 필드가 지정되지 않은 파일에서 전체 POST 본문을 가져오려면 files 매개 변수를 사용하지 말고 파일을 데이터로 직접 게시하십시오. 그렇지 않으면 설정되지 않으므로 내용 유형 헤더도 설정할 수 있습니다. Python requests - POST data from a file 를 참조하십시오.

 

 

 

 가장 최근 달린 Solution 

You can send any file via post api while calling the API just need to mention files={'any_key': fobj}

API를 호출하는 동안 post api를 통해 파일을 보낼 수 있습니다. files={'any_key': fobj} 언급하기만 하면 됩니다

 

import requests
import json
    
url = "https://request-url.com"
 
headers = {"Content-Type": "application/json; charset=utf-8"}
    
with open(filepath, 'rb') as fobj:
    response = requests.post(url, headers=headers, files={'file': fobj})
 
print("Status Code", response.status_code)
print("JSON Response ", response.json())

 

 

출처 : https://stackoverflow.com/questions/22567306/how-to-upload-file-with-python-requests

반응형
댓글
공지사항
최근에 올라온 글