在Python 3中为HTTP请求创建带有二进制组件的多部分MIME消息 [英] Creating a multi-part MIME message with a binary component for an HTTP request in Python 3
问题描述
我正在尝试使用Python 3.3中的MIMEApplication对二进制文件进行编码,作为多部分MIME HTTP POST的一部分.我有一个问题,即使所有内容都设置为二进制字节,字符0x0d仍被重新解释为换行0xa.
I'm trying to encode a binary file with MIMEApplication in Python 3.3, as part of a multi-part MIME HTTP POST. I have a problem that character 0x0d gets reinterpreted as a newline 0xa, despite everything being set to binary bytes.
这是一个最小的测试方案,其中包含一个0x0d的二进制字符串,会被误解:
Here's a minimal test scenario, with a binary string with a 0x0d in it, getting misinterpreted:
from email.encoders import encode_noop
from email.generator import BytesGenerator
from email.mime.application import MIMEApplication
import io
app = MIMEApplication(b'Q\x0dQ', _encoder=encode_noop)
b = io.BytesIO()
g = BytesGenerator(b)
g.flatten(app)
for i in b.getvalue()[-3:]:
print("%02x " % i, end="")
print()
输出为:51 0a 51
何时应为51 0d 51
请注意,这是为多部分HTTP POST消息生成二进制部分.
Note that this is to generate a binary part for a multipart http POST message.
推荐答案
我能够通过将虚拟标记"作为MIMEApplication内容来解决我的问题,然后在生成MIME消息后替换为真实的二进制文本:
I was able to solve my problem by putting a dummy 'marker' in as the MIMEApplication contents, then substituting in the real binary text after generating the MIME message:
from email.encoders import encode_noop
from email.generator import BytesGenerator
from email.mime.application import MIMEApplication
import io
# Actual binary "file" I want to encode (in real life, this is a file read from disk)
bytesToEncode = b'Q\x0dQ'
# unique marker that we can find and replace after message generation
binarymarker = b'GuadsfjfDaadtjhqadsfqerasdfiojBDSFGgg'
app = MIMEApplication(binarymarker, _encoder=encode_noop)
b = io.BytesIO()
g = BytesGenerator(b)
g.flatten(app, linesep='\r\n') # linesep for HTTP-compliant header line endings
# replace the marker with the actual binary data, then you have the output you want!
body = b.getvalue().replace(binarymarker, bytesToEncode)
此后,body
具有我想要的值,而不会弄乱二进制字节:
After this, body
has the value I want, without messing up the binary bytes:
b'Content-Type: application/octet-stream\r\nMIME-Version: 1.0\r\n\r\nQ\rQ'
对于多部分消息,您只需要首先汇编多部分消息,然后最后进行replace().
For a multi-part message, you just assemble the multipart message first, then do the replace() at the end.
这篇关于在Python 3中为HTTP请求创建带有二进制组件的多部分MIME消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!