Stop processing Flask route if request aborted

There is a potentially… hacky solution to your problem. Flask has the ability to stream content back to the user via a generator. The hacky part would be streaming blank data as a check to see if the connection is still open and then when your content is finished the generator could produce the actual image. Your generator could check to see if processing is done and return None or "" or whatever if it’s not finished.

from flask import Response

@app.route('/image')
def generate_large_image():
    def generate():
        while True:
            if not processing_finished():
                yield ""
            else:
                yield get_image()
    return Response(generate(), mimetype="image/jpeg")

I don’t know what exception you’ll get if the client closes the connection but I’m willing to bet its error: [Errno 32] Broken pipe

Leave a Comment