Python请求,如何向multipart/form-data请求添加内容类型

Yas*_*rsy 4 python upload http file python-requests

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

仅当正文包含属性 Content-Type:i mage/png not as Request Header 时,远程 API 才接受任何请求

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

此图片上的此请求被拒绝

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

查看突出显示的文本

有效请求

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

这是我的代码:

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

ses = requests.session()
res = ses.put(url=u,files=files,headers=myheaders,proxies=proxdic)
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 10

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

为了将来参考,旧相关问题中的此评论解释了所有变化:

# 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)}
Run Code Online (Sandbox Code Playgroud)