Python 3.4-使用标准库的多部分Post

Python 3.4-使用标准库的多部分Post,python,python-3.x,post,urllib,Python,Python 3.x,Post,Urllib,有没有人举过一个例子来说明如何在Python3.4中进行多部分post而不使用第三方库(如请求) 我在将旧的Python2代码移植到Python3.4时遇到问题 以下是python 2编码代码: def _encode_multipart_formdata(self, fields, files): boundary = mimetools.choose_boundary() buf = StringIO() for (key, value) in fields.iter

有没有人举过一个例子来说明如何在Python3.4中进行多部分post而不使用第三方库(如请求)

我在将旧的Python2代码移植到Python3.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。选择以下内容作为_boundary():

import email.generator
print (email.generator._make_boundary())
def _get_content_type(self, filename):
        return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
对于_get_content_type3()方法,我将执行以下操作:

import email.generator
print (email.generator._make_boundary())
def _get_content_type(self, filename):
        return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
当我在使用Python3.4时将StringIO更改为BytesIO时,数据似乎从未放入POST方法中


有什么建议吗?

是的,
email.generator.\u make\u 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}\r\n'
            'Content-Disposition: form-data; name="{key}"\r\n\r\n'
            '{value}\r\n'.format(
                boundary=boundary, key=key, value=value))

    for (key, filepath, filename) in files:
        if os.path.isfile(filepath):
            textwriter.write(
                '--{boundary}\r\n'
                'Content-Disposition: form-data; name="{key}"; '
                'filename="{filename}"\r\n'
                'Content-Type: {content_type}\r\n\r\n'.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('\r\n')

    textwriter.write('--{}--\r\n\r\n'.format(boundary))
    content_type = 'multipart/form-data; boundary={}'.format(boundary)
    return content_type, buf.getvalue()
这使用了一个函数来简化标题的格式化和编码(
bytes
对象不支持格式化操作;您必须等待Python 3.5添加了
%
支持)

如果你坚持在整个工作中使用
电子邮件
软件包,请考虑到你将需要两倍的内存;一次保存
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'\r\n\r\n')[-1]

除此之外,结果基本相同,添加了一些
MIME版本
内容传输编码
标题。

提示:查看请求是如何完成的,然后再执行。@i您是认真的吗?根本没有帮助?相关:。另见。它们都提供了在Python 2和3上工作的解决方案,有
poster
(纯Python,独立,不支持Python 3?)、
urlib3.filepost
(可能取决于其他部分)、distutils'upload_file`(专门用于将文件上载到pypi)、
MultipartPostHandler
(Python 2),@J.F.Sebastian的补丁程序:但是OP要求没有第三方库解决方案,所以现在我们有了另一个。我只是很惊讶stdlib中的
email.mime
包中没有
multipart\u encode();您需要构建一个
消息
对象树,生成的消息包含完整的电子邮件结构,而不仅仅是编码的多部分正文。然后您必须再次删除额外的标题。@MartijnPieters-谢谢,我现在要测试一下!