Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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.

1 Answer

0 votes
by (25.1k points)

You should use files= parameter for posting multipart files.

Example:

import requests

def get_predictions(path):

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

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

   pprint(response.text)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...