有没有人有一个例子,如何在Python 3.4中做一个多部分的帖子,而不使用第三方库,如请求?
我在将旧的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('--%srn' % boundary)
buf.write('Content-Disposition: form-data; name="%s"' % key)
buf.write('rnrn' + self._tostr(value) + 'rn')
for (key, filepath, filename) in files:
if os.path.isfile(filepath):
buf.write('--%srn' % boundary)
buf.write('Content-Disposition: form-data; name="%s"; filename="%s"rn' % (key, filename))
buf.write('Content-Type: %srn' % (self._get_content_type3(filename)))
file = open(filepath, "rb")
try:
buf.write('rn' + file.read() + 'rn')
finally:
file.close()
buf.write('--' + boundary + '--rnrn')
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方法中。
有什么建议吗?
是的,email.generator._make_boundary()
可以工作:
import email.generator
import io
import shutil
def _encode_multipart_formdata(self, fields, files):
boundary = email.generator._make_boundary()
buf = io.BytesIO()
textwriter = io.TextIOWrapper(
buf, 'utf8', newline='', write_through=True)
for (key, value) in fields.items():
textwriter.write(
'--{boundary}rn'
'Content-Disposition: form-data; name="{key}"rnrn'
'{value}rn'.format(
boundary=boundary, key=key, value=value))
for (key, filepath, filename) in files:
if os.path.isfile(filepath):
textwriter.write(
'--{boundary}rn'
'Content-Disposition: form-data; name="{key}"; '
'filename="{filename}"rn'
'Content-Type: {content_type}rnrn'.format(
boundary=boundary, key=key, filename=filename,
content_type=self._get_content_type3(filename)))
with open(filepath, "rb") as f:
shutil.copyfileobj(f, buf)
textwriter.write('rn')
textwriter.write('--{}--rnrn'.format(boundary))
content_type = 'multipart/form-data; boundary={}'.format(boundary)
return content_type, buf.getvalue()
使用io.TextIOWrapper()
对象来简化标头的格式化和编码(bytes
对象不支持格式化操作;你必须等待Python 3.5加入%
支持)。
如果你坚持使用email
包的整个工作,考虑到你将需要两倍的内存;一次保存email.mime
对象,另一次保存写入结果:
from email.mime import multipart, nonmultipart, text
from email.generator import BytesGenerator
from email import policy
from io import BytesIO
def _encode_multipart_formdata(self, fields, files):
msg = multipart.MIMEMultipart('form-data')
for (key, value) in fields.items():
part = text.MIMEText(value)
part['Content-Disposition'] = 'form-data; name="{}"'.format(key)
msg.attach(part)
for (key, filepath, filename) in files:
if os.path.isfile(filepath):
ct = self._get_content_type3(filename)
part = nonmultipart.MIMENonMultipart(*ct.split('/'))
part['Content-Disposition'] = (
'form-data; name="{}"; filename="{}"'.format(
key, filename))
with open(filepath, "rb") as f:
part.set_payload(f.read())
msg.attach(part)
body = BytesIO()
generator = BytesGenerator(
body, mangle_from_=False, policy=policy.HTTP)
generator.flatten(msg)
return msg['content-type'], body.getvalue().partition(b'rnrn')[-1]
结果基本上是相同的,除了一些MIME-Version
和Content-Transfer-Encoding
头。