我正在尝试使用 httplib2 发布一个 HTTP 请求,其中包含一些 xml 和一些使用此信息集的二进制数据:
MIME-Version: 1.0
Content-Type: Multipart/Related;boundary=MIME_boundary;
...
--MIME_boundary
Content-Type: application/xop+xml;
// [the xml string goes here...]
--MIME_boundary
Content-Type: image/png
Content-Transfer-Encoding: binary
Content-ID: <http://example.org/me.png>
// [the binary octets for png goes here...]
我的做法是生成一个txt文件,然后填写xml和二进制数据。
我在将二进制数据写入从 png 读取的文件时遇到问题:
pngfile = open(pngfile, "rb")
bindata = pngfile.read()
执行此操作的最佳方法是什么?
请您参考如下方法:
我的建议是使用 Python 的标准 mime 库,如 these examples . 试试这个:
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
# Attach XML
xml = MIMEBase('application','xop+xml')
xml.set_payload(<xml data here>)
msg.attach(xml)
# Attach image
img = MIMEImage(<image data here>, _subtype='png')
msg.attach(img)
# Export the infoset
print msg.as_string()
