Python请求,如何将内容类型添加到multipart / form-data请求 [英] Python requests, how to add content-type to multipart/form-data request

查看:1361
本文介绍了Python请求,如何将内容类型添加到multipart / form-data请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python请求使用PUT方法上传文件。

I Use python requests to upload a file with PUT method.

远程API只有在正文包含属性时接受任何请求
Content-Type :我mage / png不是请求标题

The remote API Accept any request only if the body contains an attribute Content-Type:i mage/png not as Request Header

当我使用python请求时,请求被拒绝,因为缺少属性

When i use python requests , the request rejected because missing attribute

我尝试使用代理,并在添加缺失属性后,已接受

I tried to use a proxy and after adding the missing attribute , it was accepted

参见突出显示的文字

但我不能以编程方式添加它,我该怎么办?

but i can not programmatically add it , How can i do it?

这是我的代码:

files = {'location[logo]': open(fileinput,'rb')} 

ses = requests.session()
res = ses.put(url=u,files=files,headers=myheaders,proxies=proxdic)


推荐答案

根据[docs] [1,你需要为元组,文件名和内容类型添加两个参数:

As per the [docs][1, you need to add two more arguments to the tuple, filename and the content type:

#         filed name         filename    file object      content=type
files = {'location[logo]': ("name.png", open(fileinput),'image/png')}

您可以看到一个示例示例下面:

You can see a sample an example below:

In [1]: import requests

In [2]: files = {'location[logo]': ("foo.png", open("/home/foo.png"),'image/png')}

In [3]: 

In [3]: ses = requests.session()

In [4]: res = ses.put("http://httpbin.org/put",files=files)

In [5]: print(res.request.body[:200])
--0b8309abf91e45cb8df49e15208b8bbc
Content-Disposition: form-data; name="location[logo]"; filename="foo.png"
Content-Type: image/png

�PNG

IHDR��:d�tEXtSoftw

供将来参考,此评论解释了所有变体:

For future reference, this comment in a old related issue explains all variations:

# 1-tuple (not a tuple at all)
{fieldname: file_object}

# 2-tuple
{fieldname: (filename, file_object)}

# 3-tuple
{fieldname: (filename, file_object, content_type)}

# 4-tuple
{fieldname: (filename, file_object, content_type, headers)}

这篇关于Python请求,如何将内容类型添加到multipart / form-data请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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