【发布时间】:2015-09-26 15:28:41
【问题描述】:
有没有人举例说明如何在 Python 3.4 中不使用请求之类的 3rd 方库进行多部分发布?
我在将旧的 Python 2 代码移植到 Python 3.4 时遇到问题。
这里是python 2的编码代码:
def _encode_multipart_formdata(self, fields, files):
boundary = mimetools.choose_boundary()
buf = StringIO()
for (key, value) in fields.iteritems():
buf.write('--%s\r\n' % boundary)
buf.write('Content-Disposition: form-data; name="%s"' % key)
buf.write('\r\n\r\n' + self._tostr(value) + '\r\n')
for (key, filepath, filename) in files:
if os.path.isfile(filepath):
buf.write('--%s\r\n' % boundary)
buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
buf.write('Content-Type: %s\r\n' % (self._get_content_type3(filename)))
file = open(filepath, "rb")
try:
buf.write('\r\n' + file.read() + '\r\n')
finally:
file.close()
buf.write('--' + boundary + '--\r\n\r\n')
buf = buf.getvalue()
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, buf
我发现我可以将 mimetools.choose_boundary() 替换为以下内容:
import email.generator
print (email.generator._make_boundary())
对于 _get_content_type3() 方法,我正在执行以下操作:
def _get_content_type(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
当我在使用 Python3.4 中将 StringIO 更改为 BytesIO 时,数据似乎从未放入 POST 方法中。
有什么建议吗?
【问题讨论】:
-
提示:看看 requests 是怎么做的,然后再做。
-
@IanAuld 你是认真的吗?一点帮助都没有?
-
相关:Python standard library to POST multipart/form-data encoded data。另请参阅
urllib3.filepost。两者都提供适用于 Python 2 和 3 的解决方案
标签: python python-3.x post urllib