multipart/form-data로 인코딩 된 데이터를 POST하고 싶습니다. 나는 그것을하는 외부 모듈을 찾았습니다 : http://atlee.ca/software/poster/index.html 그러나 나는이 의존성을 피하고 싶습니다. 표준 라이브러리를 사용하여이를 수행 할 수있는 방법이 있습니까?POST multipart/form-data로 인코딩 된 파이썬 표준 라이브러리
감사
multipart/form-data로 인코딩 된 데이터를 POST하고 싶습니다. 나는 그것을하는 외부 모듈을 찾았습니다 : http://atlee.ca/software/poster/index.html 그러나 나는이 의존성을 피하고 싶습니다. 표준 라이브러리를 사용하여이를 수행 할 수있는 방법이 있습니까?POST multipart/form-data로 인코딩 된 파이썬 표준 라이브러리
감사
표준 라이브러리 does not currently support that. 그래도 대체 할 수있는 코드의 짧은 부분이 포함 된 cookbook recipe이 있습니다. 그러나 대안에 대한 오랜 토론과 함께.
stdlib를 사용하면이 작업을 빨리 수행 할 수 없습니다. 이 PyMOTW에서 MultiPartForm
클래스를 참조하십시오. 당신은 아마 사용하거나 당신이 필요로하는 무엇이든 달성하는 것을 수정할 수 있습니다
그것은 오래된 스레드하지만 여전히 인기있는 한, 그래서 여기 내 공헌은 표준 모듈을 사용하고 있습니다.
아이디어는 here과 동일하지만 파이썬 2.x 및 파이썬 3.x를 지원합니다. 불필요한 메모리 사용을 막는 바디 생성기도 있습니다.
import codecs
import mimetypes
import sys
import uuid
try:
import io
except ImportError:
pass # io is requiered in python3 but not available in python2
class MultipartFormdataEncoder(object):
def __init__(self):
self.boundary = uuid.uuid4().hex
self.content_type = 'multipart/form-data; boundary={}'.format(self.boundary)
@classmethod
def u(cls, s):
if sys.hexversion < 0x03000000 and isinstance(s, str):
s = s.decode('utf-8')
if sys.hexversion >= 0x03000000 and isinstance(s, bytes):
s = s.decode('utf-8')
return s
def iter(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, file-type) elements for data to be uploaded as files
Yield body's chunk as bytes
"""
encoder = codecs.getencoder('utf-8')
for (key, value) in fields:
key = self.u(key)
yield encoder('--{}\r\n'.format(self.boundary))
yield encoder(self.u('Content-Disposition: form-data; name="{}"\r\n').format(key))
yield encoder('\r\n')
if isinstance(value, int) or isinstance(value, float):
value = str(value)
yield encoder(self.u(value))
yield encoder('\r\n')
for (key, filename, fd) in files:
key = self.u(key)
filename = self.u(filename)
yield encoder('--{}\r\n'.format(self.boundary))
yield encoder(self.u('Content-Disposition: form-data; name="{}"; filename="{}"\r\n').format(key, filename))
yield encoder('Content-Type: {}\r\n'.format(mimetypes.guess_type(filename)[0] or 'application/octet-stream'))
yield encoder('\r\n')
with fd:
buff = fd.read()
yield (buff, len(buff))
yield encoder('\r\n')
yield encoder('--{}--\r\n'.format(self.boundary))
def encode(self, fields, files):
body = io.BytesIO()
for chunk, chunk_len in self.iter(fields, files):
body.write(chunk)
return self.content_type, body.getvalue()
데모
# some utf8 key/value pairs
fields = [('প্রায়', 42), ('bar', b'23'), ('foo', 'ން:')]
files = [('myfile', 'image.jpg', open('image.jpg', 'rb'))]
# iterate and write chunk in a socket
content_type, body = MultipartFormdataEncoder().encode(fields, files)
에만 표준 라이브러리 파이썬 3 일 마지막으로 솔루션입니다. –