Python requests,如何在multipart/form-data请求中添加content-type

6
我使用Python的requests模块以PUT方法上传文件。 远程API仅接受包含属性Content-Type:image/png而不是请求头的请求。 当我使用Python的requests模块时,由于缺少属性,请求被拒绝。

This request is rejected on this image

我尝试使用代理,添加了缺失的属性后,它被接受了。

请查看高亮文本。

Valid request

但是我无法通过编程的方式添加它,我该怎么做?
这是我的代码:
files = {'location[logo]': open(fileinput,'rb')} 

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

PUT包含单个对象,需要使用POST来扩展“文件名或任何其他键”。 - dsgdfg
API仅允许使用PUT方法,因此每个请求只能上传单个文件。 - Yasser Gersy
1个回答

11
根据[文档][1],您需要向元组中添加两个参数,文件名和内容类型:

根据[文档][1],您需要向元组中添加两个参数,文件名和内容类型:

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

下面是一个示例:

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

为今后参考,这条评论在一个旧相关问题中解释了所有的变化。

# 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)}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接