Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-Type in for individual files in python requests

I want to request to my server running in python flask with file and some meta information. Hence my request content-Type will be 'multipart/form-data. Is there a way i can set the content type of file like image/jpg, image/gif etc... How do i set the content-type for the file. Is it possible or not

like image 613
kishore Avatar asked Nov 27 '13 14:11

kishore


People also ask

How do you add a Content-Type to a request header in Python?

To send the Content-Type header using Curl, you need to use the -H command-line option. For example, you can use the -H "Content-Type: application/json" command-line parameter for JSON data. Data is passed to Curl using the -d command-line option.

What is request content in Python?

Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc.

What is Content-Type Python?

Client Request with Content-Type Header [Python Code] The 'Content-Type: application/json' header tells the server that the request body contains a JSON string. The Python code was automatically generated for the Client Request Content Type Header example.


2 Answers

If you make each file specification a tuple, you can specify the mime type as a third parameter:

files = {
    'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'),
    'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'),
}
response = requests.post(url, files=files)

You can give a 4th parameter as well, which must be a dictionary with additional headers for each part.

like image 146
Martijn Pieters Avatar answered Oct 16 '22 10:10

Martijn Pieters


reference

    import requests

    url = "http://png_upload_example/upload"
    # files = [(<key>, (<filename>, open(<file location>, 'rb'), <content type>))]
    files = [('upload', ('thumbnail.png', open('thumbnail.png', 'rb'), 'image/png'))]

    response = requests.request("POST", url, files = files)
like image 38
Ben Avatar answered Oct 16 '22 10:10

Ben