Python requests, how to add content-type to multip

2019-07-14 02:39发布

问题:

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