如何在python中发送带有请求的"multipart/related"? [英] How to send a “multipart/related” with requests in python?

查看:319
本文介绍了如何在python中发送带有请求的"multipart/related"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python中的请求发送多部分/相关消息.该脚本看起来很简单,除了请求似乎只允许发送多部分/表单数据消息,尽管它们的文档没有明确说明这种方式.

I'm trying to send a multipart/related message using requests in Python. The script seems simple enough, except that requests only seems to allow multipart/form-data messages to be sent, though their documentation does not clearly state this one way or another.

我的用例是发送带有附件的肥皂.我可以提供一个字典,其中包含两个文件,它们的内容分别是测试肥皂消息和要发送的测试文档.第一个包含所有说明的肥皂消息,第二个是实际文档.

My use case is sending soap with attachments. I can provide a dictionary with the two files whose contents are a test soap-message, and a test document that I'm trying to send. The first contains the soap message with all the instructions, the second is the actual document.

但是,如果我未指定标头值,则在使用files选项时,请求似乎仅使用multipart/form-data.但是,如果我尝试指定不同的多部分类型来指定标头,则请求似乎未添加mime边界信息.

However, if I don't specify a headers value, requests only seems to use multipart/form-data when using the files option. But if I specify headers in an attempt to specify a different multipart type, requests does not seem to add in the mime boundary information.

url = 'http://10.10.10.90:8020/foo'
headers = {'content-type': 'multipart/related'}
files = {'submission': open('submission_set.xml', 'rb'), 'document': open('document.txt', 'rb')}
response = requests.post(url, data=data, headers=headers)
print response.text

有没有一种方法可以使用请求完成此任务?还是我应该查看另一种工具?

Is there a way to get this done using requests? Or is there another tool that I should be looking at?

推荐答案

您必须自己创建MIME编码.您可以使用 email.mime 软件包来做到这一点:

You'll have to create the MIME encoding yourself. You can do so with the email.mime package:

import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

related = MIMEMultipart('related')

submission = MIMEText('text', 'xml', 'utf8')
submission.set_payload(open('submission_set.xml', 'rb').read())
related.attach(submission)

document = MIMEText('text', 'plain')
document.set_payload(open('document.txt', 'rb').read())
related.attach(document)

body = related.as_string().split('\n\n', 1)[1]
headers = dict(related.items())

r = requests.post(url, data=body, headers=headers)

我假设XML文件使用UTF-8,您可能还想为document条目设置一个字符集.

I presumed the XML file uses UTF-8, you probably want to set a character set for the document entry as well.

requests仅知道如何创建multipart/form-data帖子正文; multipart/related不常用.

requests only knows how to create multipart/form-data post bodies; the multipart/related is not commonly used.

这篇关于如何在python中发送带有请求的"multipart/related"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆