2016-09-28 43 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

所以單個文件的工作,由於 –

相關問題