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

2024/9/23 12:31:37

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

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 requestsIn [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�PNGIHDR��: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://en.xdnf.cn/q/71827.html

Related Q&A

Django Year/Month based posts archive

im new to Django and started an application, i did the models, views, templates, but i want to add some kind of archive to the bottom of the page, something like this http://www.flickr.com/photos/ion…

ValueError: You are trying to load a weight file containing 6 layers into a model with 0

I have a simple keras model. After the model is saved. I am unable to load the model. This is the error I get after instantiating the model and trying to load weights:Using TensorFlow backend. Tracebac…

cProfile with imports

Im currently in the process of learn how to use cProfile and I have a few doubts.Im currently trying to profile the following script:import timedef fast():print("Fast!")def slow():time.sleep(…

Python AWS Lambda 301 redirect

I have a lambda handler written in Python and I wish to perform a 301 redirect to the browser. I have no idea how I can configure the response Location header (or the status code) -- the documentation …

Google Authenticator code does not match server generated code

BackgroundIm currently working on a two-factor authentication system where user are able to authenticate using their smartphone. Before the user can make use of their device they need to verify it firs…

Gekko Non-Linear optimization, object type error in constraint function evaluating if statement

Im trying to solve a non-linear optimization problem. Ive duplicated my issue by creating the code below. Python returns TypeError: object of type int has no len(). How can I include an IF statement in…

Store large dictionary to file in Python

I have a dictionary with many entries and a huge vector as values. These vectors can be 60.000 dimensions large and I have about 60.000 entries in the dictionary. To save time, I want to store this aft…

Python: override __str__ in an exception instance

Im trying to override the printed output from an Exception subclass in Python after the exception has been raised and Im having no luck getting my override to actually be called.def str_override(self):…

How hide/show a field upon selection of a radio button in django admin?

models.pyfrom django.db import models from django.contrib.auth.models import UserSTATUS_CHOICES = ((1, Accepted),(0, Rejected),) class Leave(models.Model):----------------status = models.IntegerField(c…

format/round numerical legend label in GeoPandas

Im looking for a way to format/round the numerical legend labels in those maps produced by .plot() function in GeoPandas. For example:gdf.plot(column=pop2010, scheme=QUANTILES, k=4)This gives me a lege…