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

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

问题描述

我正在尝试使用 Python 中的请求发送多部分/相关消息.该脚本看起来很简单,除了请求似乎只允许发送 multipart/form-data 消息,尽管他们的文档没有清楚地说明这一点或另一种方式.

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.

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

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.

但是,如果我不指定 headers 值,则在使用 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('

', 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中发送带有请求的“多部分/相关"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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