How to get response data consisting both image file and values in flask server post response?

Sending image to the flask server and do object detection on that and send back that image as a response and no of object detected variable value. Flask route function is as below

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['image']
    im =

    total_count = 0
    for i in keypoints:
        total_count = total_count + 1
    im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    file_object = io.BytesIO()
    img = Image.fromarray(im_with_keypoints.astype('uint8'))

    # write PNG in file-object, 'JPEG')

    # move to beginning of file so `send_file()` it will read from start

    return send_file(file_object, mimetype='image/jpeg')

when I do post a request by uploading an image I get the processed image back on POSTMAN but I need to get the value of variable total_count along with the image. I tried calling like this

return '{} {}'.format(total_count,send_file(file_object, mimetype='image/jpeg'))

but I got output as 11 <Response streamed [200 OK]> where the image is stored as object form, is there a way to get the image along with the total_count value as a response? Any suggestion or example on the way of getting both response which is Image and variable total_count?

1 answer

  • answered 2021-06-23 15:07 mclslee

    Off the top of my head, there are a couple of things you could do, below are pseudocoded-ish versions:

    • Make a custom header in the response and grab it from the headers with whatever is calling this endpoint
    from flask import make_response, send_file    
    response = make_response(send_file(file_object, mimetype='image/jpeg'))
    response.headers['Total-Count'] = total_count #might have to make it a string
    return response


    • Send the file with the total_count as part of the filename and parse it out from whatever is calling this endpoint
    from flask import send_file
    file_name = f"{total_count}_image.jpeg"
    return send_file(file_object, mimetype="image/jpeg", as_attachment=True, attachment_filename=file_name)