Nithin Varghese
Nithin Varghese

Reputation: 923

why sending image in python using form with post is not working

Trying to send an image using Requests package to Flask server using forms with post. But the flask server is not able to parse the key image. How to send the image in proper format with requests using forms.

Flask server.py

@app.route('/api/<model_name>/predict/', methods=['POST'])
def predict(model_name):

    if "image" in request.files.keys():
        return jsonify({"msg": "key found"})

    print("image", request.files)
    return str(), 200

Requests client.py

def get_predictions(path):

   url = "http://localhost:9020/api/fasterrcnn/predict/"

   payload = {"image": (path.name, open(path, "rb"), "image/jpeg")}
   headers = {'content-type': "multipart/form-data"}
   response = requests.post(
       url, data=payload, headers=headers, stream=True)

   pprint(response.text)

Could someone please tell me the possible cause and solution? If I've missed out anything, over- or under-emphasized a specific point, let me know in the comments.

Upvotes: 1

Views: 69

Answers (1)

Ivan Vinogradov
Ivan Vinogradov

Reputation: 4473

requests documentation page states that you should use files= parameter for posting multipart files.

Example:

import requests

def get_predictions(path):
   url = "http://localhost:9020/api/fasterrcnn/predict/"

   files = {"image": (path.name, open(path, "rb"), "image/jpeg")}
   response = requests.post(url, files=files)

   pprint(response.text)

Upvotes: 1

Related Questions