Home > OS >  Python Post request for image
Python Post request for image

Time:09-13

I'm trying to convert this request into Python's requests but it seems like I got some error. It works fine with curl. The api I used: https://www.reddit.com/r/MachineLearning/comments/ikxck0/p_turn_images_into_cartoon_ready_to_use_api_is/

(myobama.png) is my local image

curl -X POST "https://master-white-box-cartoonization-psi1104.endpoint.ainize.ai/predict" -H "accept: image/jpg" -H "Content-Type: multipart/form-data" -F "file_type=image" -F "[email protected];type=image/png" > img.png 

My current Python post request, which results in {"message":"Error! Please upload another file"}

import requests

headers = {
    'accept': 'image/jpg',
    'Content-Type': 'multipart/form-data',
}

files = {
    'file_type': 'image',
    'source': open('myobama.png;type=image/png', 'rb'),
}

response = requests.post('https://master-white-box-cartoonization-psi1104.endpoint.ainize.ai/predict', headers=headers, files=files)

CodePudding user response:

Checking the documentation it seems that your files dictionary is missing the key file. See https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file

EDITED Please, check UPDATED section. This is no longer valid.

files = { 'file': ('myobama.png', open('myobama.png;type=image/png', 'rb'), 'image/png')}

UPDATED

After some curl / requests comparison and debugging, this should be the headers and files objects:

headers = {
    'Accept': 'image/png'
}

files = { 
    'file_type': (None, 'image'),
    'source': ('myobama.png', open('myobama.png', 'rb'), 'image/png')
}

I tested it myself and it works as expected. Hope it helps.

  • Related