Python请求,如何将内容类型添加到多部分/表单数据请求

标签 python file http upload python-requests

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

远程 API 仅当正文包含属性时才接受任何请求 Content-Type:i mage/png 不是请求头

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

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)

最佳答案

根据 [docs][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

供将来引用,this comment在旧的相关问题中解释了所有变化:

# 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请求,如何将内容类型添加到多部分/表单数据请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39738525/

相关文章:

python - 临时文件目录最终是否被系统清除

Python 3 获取当前列表循环的深度

html - 如何使用 Go 发布文件数组?

python - 为什么 readline() 不返回原始文本?

asp.net - http header 中非ascii值的当前状态?

python - 比例变异性代码

c - 在 C 中编辑文件的特定行

c# - 使用异步和等待的死锁

php - Guzzle 6,获取请求字符串

python - 如何查看队列中的消息