我想POST多部分/表格數據編碼數據。 我發現了一個外部模塊:http://atlee.ca/software/poster/index.html 但是我寧願避免這種依賴性。有沒有辦法使用標準庫來做到這一點?Python標準庫以POST多部分/表格數據編碼數據
感謝
我想POST多部分/表格數據編碼數據。 我發現了一個外部模塊:http://atlee.ca/software/poster/index.html 但是我寧願避免這種依賴性。有沒有辦法使用標準庫來做到這一點?Python標準庫以POST多部分/表格數據編碼數據
感謝
標準庫does not currently support that。有cookbook recipe,其中包含一段相當短的代碼,但您可能需要複製這些代碼,以及長時間討論備選方案。
你不能用stdlib快速做到這一點。 Howevewr,請參閱此PyMOTW中的MultiPartForm
類。你也許可以使用或修改,要實現任何你需要:
這是一個古老的線程,但仍然是一個受歡迎的人,所以在這裏只採用標準模塊我的貢獻。
該想法與here相同,但支持Python 2.x和Python 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)
最後僅與標準庫爲Python 3有效的解決方案。 – 2015-04-10 10:15:37