用于发布多部分/表单数据编码数据的Python标准库
我想发布多部分/表单数据编码数据。 我发现有一个外部模块可以: 然而,我宁愿避免这种依赖。有没有办法使用标准库来实现这一点用于发布多部分/表单数据编码数据的Python标准库,python,encoding,post,urllib,multipart,Python,Encoding,Post,Urllib,Multipart,我想发布多部分/表单数据编码数据。 我发现有一个外部模块可以: 然而,我宁愿避免这种依赖。有没有办法使用标准库来实现这一点 谢谢标准库。不过,其中包括一段相当短的代码,您可能只想复制它,并对替代方案进行了长时间的讨论。使用stdlib不能很快做到这一点。但是,请参见本PyMOTW中的多部分表单类。您可能可以使用或修改它来完成您需要的任何任务: 这是一个古老的线程,但仍然是一个流行的线程,因此这里是我仅使用标准模块的贡献 其思想与相同,但支持Python2.x和Python3.x。 它还有一个
谢谢标准库。不过,其中包括一段相当短的代码,您可能只想复制它,并对替代方案进行了长时间的讨论。使用stdlib不能很快做到这一点。但是,请参见本PyMOTW中的
多部分表单
类。您可能可以使用或修改它来完成您需要的任何任务:
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()
最后是一个只适用于标准库的Python 3解决方案。。
# 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)