2016-09-28 62 views
2

I使用PUT方法使用python请求上传文件。Python请求,如何将内容类型添加到多部分/表单数据请求

远程API接受仅当主体包含一个属性 内容类型的任何请求:ⅰ法师/不为png作为请求报头

当我用蟒请求,该请求被拒绝,因为缺少属性

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) 
+0

PUT包括单个对象,需要POST用于扩展文件名'或任何额外key' – dsgdfg

+0

该API仅允许PUT和每个请求 –

回答

1

由于每[文档] [1,你需要两个参数添加到元组,文件名和内容类型:

#   filed 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在老相关的问题explai纳秒所有变化:

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

所以单个文件的工作,由于 –