python 요청으로 파일을 업로드하려면 어떻게 해야 합니까?
Python requests library를 사용하여 파일을 업로드하는 간단한 작업을 하고 있습니다.Stack Overflow를 검색했는데, 같은 문제가 있는 사람은 없는 것 같습니다.즉, 파일이 서버에 의해서 수신되지 않는 것입니다.
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)
'upload_file' 키워드의 값을 파일명으로 입력하고 있습니다.이 값을 공백으로 두면
Error - You must select a file to upload!
그리고 이제 나는
File file.txt of size bytes is uploaded successfully!
Query service results: There were 0 lines.
파일이 비어 있는 경우에만 표시됩니다.그래서 나는 내 파일을 어떻게 성공적으로 보내야 할지 막막막해요.이 웹 사이트에 접속하여 폼을 수동으로 입력하면 일치하는 오브젝트 목록이 반환되기 때문에 파일이 작동한다는 것을 알고 있습니다.힌트 주시면 정말 감사하겠습니다.
기타 관련 스레드(문제 해결이 안 됨):
- POST를 사용하여 Python 스크립트에서 파일 보내기
- http://docs.python-requests.org/en/latest/user/quickstart/ #response-content
- 요청을 사용하여 파일 업로드 및 추가 데이터 전송
- http://docs.python-requests.org/en/latest/user/advanced/ #body-content-displicate
ifupload_file을 사용하다
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
★★★★★★★★★★★★★★★★★」requests는, POST 를 한 복수 합니다.upload_file의 내용으로 file.txtfilename을 클릭합니다.
파일명은 특정 필드의 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--
해 주세요.filename="file.txt"파라미터를 지정합니다.
에는 할 수 .files(2~4월)에 있다그 값 및헤더의 입니다.「 」 、 「 」 、 「 」 、 「 」 、 「 content - type 」 。
files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}
이것에 의해, 옵션의 헤더는 생략하고, 대체 파일명과 컨텐츠유형이 설정됩니다.
(다른 필드를 지정하지 않고) 파일로부터 POST 본문 전체를 취득하는 경우는,files파라미터), parameter(파라미터), parameter(파라미터), parameter(파라미터)로 투고합니다.data. 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 이런Content-Type그렇지 않으면 아무것도 설정되지 않으므로 헤더도 마찬가지입니다.Python 요청 - 파일의 POST 데이터를 참조하십시오.
(2018) 새로운 python requests 라이브러리가 이 프로세스를 단순화했습니다. 우리는 'files' 변수를 사용하여 멀티파트 파일을 업로드하고 싶다는 신호를 보낼 수 있습니다.
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
클라이언트 업로드
Python Python을 requests라이브러리 요청 lib는 스트리밍 업로드를 지원하므로 대용량 파일 또는 스트림을 메모리에 읽지 않고 전송할 수 있습니다.
with open('massive-body', 'rb') as f:
requests.post('http://some.url/streamed', data=f)
서버측
그런 다음 파일을 에 저장합니다.server.py메모리에 로드하지 않고 스트림을 파일에 저장합니다.다음은 Flask 파일 업로드를 사용하는 예입니다.
@app.route("/upload", methods=['POST'])
def upload_file():
from werkzeug.datastructures import FileStorage
FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'OK', 200
또는 "대용량 파일 업로드 메모리 소비" 문제에 대한 수정에서 설명한 바와 같이 werkzeug 폼 데이터 파싱을 사용하여 대용량 파일 업로드(60초 이내에 st. 22 GiB 파일)에서 메모리가 비효율적으로 사용되는 것을 방지합니다.메모리 사용량은 약 13 MiB로 일정합니다).
@app.route("/upload", methods=['POST'])
def upload_file():
def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
import tempfile
tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
return tmpfile
import werkzeug, flask
stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
for fil in files.values():
app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
# Do whatever with stored file at `fil.stream.name`
return 'OK', 200
post api를 통해 어떤 파일도 전송할 수 있으며 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())
@martijn-pieters의 답변은 맞지만, 저는 여기에 약간의 콘텍스트를 추가하고 싶었습니다.data=또한 파일 및 JSON을 업로드하려는 경우 Flask 서버에서 다른 쪽으로 이동합니다.
요구측에서 이것은 Martijn의 설명대로 동작합니다.
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
다만, 플라스크측(이 POST의 반대편에 있는 수신측 웹 서버)에서는,form
@app.route("/sftp-upload", methods=["POST"])
def upload_file():
if request.method == "POST":
# the mimetype here isnt application/json
# see here: https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask
body = request.form
print(body) # <- immutable dict
body = request.get_json()아무것도 돌려주지 않습니다. body = request.get_data()파일명과 같은 많은 것을 포함한 BLOB가 반환됩니다.
여기 단점이 있습니다.클라이언트 측에서는 변경data={}로.json={}결과적으로 이 서버는 KV 쌍을 읽을 수 없습니다.이 경우 다음과 같이 {}개 이상의 본문이 생성됩니다.
r = requests.post(url, files=files, json=values). # No!
이는 서버가 사용자가 요청을 포맷하는 방법을 제어할 수 없기 때문에 좋지 않습니다.json=사용자 요청의 핵심이 됩니다.
업로드:
with open('file.txt', 'rb') as f:
files = {'upload_file': f.read()}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
다운로드(장고):
with open('file.txt', 'wb') as f:
f.write(request.FILES['upload_file'].file.read())
Ubuntu에서는 이렇게 신청할 수 있습니다.
파일을 특정 위치(임시)에 저장한 후 열어 API로 전송하다
path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
data={} #can be anything u want to pass along with File
file1 = open(path12, 'rb')
header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
res= requests.post(url,data,header)
언급URL : https://stackoverflow.com/questions/22567306/how-to-upload-file-with-python-requests
'source' 카테고리의 다른 글
| JavaScript 연산, 소수점 2자리 반올림 (0) | 2022.11.13 |
|---|---|
| Windows는 JAVA_를 무시합니다.홈: JDK를 기본값으로 설정하는 방법 (0) | 2022.11.13 |
| 속성 이름을 가진 변수가 있는 개체 속성이 있는지 확인하는 방법 (0) | 2022.11.13 |
| Larabel 5에서 쿼리를 실행하는 방법DB:: getQueryLog() 빈 어레이 반환 (0) | 2022.11.13 |
| 날짜 차이(일별 php) (0) | 2022.11.13 |