您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中创建和解析多部分HTTP请求

在Python中创建和解析多部分HTTP请求

经过一番探索,这个问题的答案变得清晰了。简短的答案是,尽管Content- Disposition在Mime编码的消息中是可选的,但web.py要求每个mime部分都需要它,以便正确解析HTTP请求。

与对此问题的其他评论相反,HTTP和电子邮件间的区别无关紧要,因为它们只是Mime消息的传输机制,仅此而已。多部分/相关(不是多部分/表单数据)消息在内容交换Web服务中很常见,这是这里的用例。但是,所提供的代码段是准确的,这使我找到了对该问题的简要介绍。

# open an HTTP connection
h1 = httplib.httpconnection('localhost:8080')

# create a mime multipart message of type multipart/related
msg = MIMEMultipart("related")

# create a mime-part containing a zip file, with a Content-Disposition header
# on the section
fp = open('file.zip', 'rb')
base = MIMEBase("application", "zip")
base['Content-Disposition'] = 'file; name="package"; filename="file.zip"'
base.set_payload(fp.read())
encoders.encode_base64(base)
msg.attach(base)

# Here's a rubbish bit: chomp through the header rows, until hitting a newline on
# its own, and read each string on the way as an HTTP header, and reading the rest
# of the message into a new variable
header_mode = True
headers = {}
body = []
for line in msg.as_string().splitlines(True):
    if line == "\n" and header_mode == True:
        header_mode = False
    if header_mode:
        (key, value) = line.split(":", 1)
        headers[key.strip()] = value.strip()
    else:
        body.append(line)
body = "".join(body)

# do the request, with the separated headers and body
h1.request("POST", "http://localhost:8080/server", body, headers)

这很容易被web.py很好地接受,因此很明显,email.mime.multipart适用于创建要通过HTTP传输的Mime消息,但其标头处理除外。

我的另一个整体想法是可伸缩性。此解决方案或此处提出的其他解决方案都无法很好地扩展,因为他们在将文件内容捆绑到mime消息中之前将文件内容读取为变量。更好的解决方案是当内容通过HTTP连接通过管道传输时可以按需序列化的解决方案。对于我来说,解决这个问题并不紧急,但是如果有解决方案,我将在这里提供解决方案。

python 2022/1/1 18:28:29 有365人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶