栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

# open an HTTP connectionh1 = httplib.HTTPConnection('localhost:8080')# create a mime multipart message of type multipart/relatedmsg = MIMEMultipart("related")# create a mime-part containing a zip file, with a Content-Disposition header# on the sectionfp = open('file.zip', 'rb')base = MIMEbase("application", "zip")base['Content-Disposition'] = 'file; name="package"; filename="file.zip"'base.set_payload(fp.read())enprers.enpre_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 variableheader_mode = Trueheaders = {}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 bodyh1.request("POST", "http://localhost:8080/server", body, headers)

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号