Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

This request is rejected on this image

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

See the highlighted text

Valid request

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)
like image 656
Yasser Gersy Avatar asked Sep 28 '16 05:09

Yasser Gersy


Video Answer


1 Answers

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

#         field 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)}
like image 172
Padraic Cunningham Avatar answered Sep 22 '22 14:09

Padraic Cunningham