Python requests, how to add content-type to multipart/form-data request

别说谁变了你拦得住时间么 提交于 2019-12-10 23:20:52

问题


I Use python requests to upload a file with PUT method.

The remote API Accept any request only if the body contains an attribute Content-Type:i mage/png not as Request Header

When i use python requests , the request rejected because missing attribute

I tried to use a proxy and after adding the missing attribute , it was accepted

See the highlighted text

but i can not programmatically add it , How can i do it?

And this is my code:

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

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

回答1:


As per the [docs][1, you need to add two more arguments to the tuple, filename and the content type:

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

You can see a sample an example below:

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

For future reference, this comment in a old related issue explains all variations:

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


来源:https://stackoverflow.com/questions/39738525/python-requests-how-to-add-content-type-to-multipart-form-data-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!