Stop processing Flask route if request aborted

后端 未结 3 521
予麋鹿
予麋鹿 2020-12-13 06:48

I have a flask REST endpoint that does some cpu-intensive image processing and takes a few seconds to return. Often, this endpoint gets called, then aborted by the client. I

3条回答
  •  [愿得一人]
    2020-12-13 07:25

    As far as I know you can't know if a connection was closed by the client during the execution because the server is not testing if the connection is open during the execution. I know that you can create your custom request_handler in your Flask application for detecting if after the request is processed the connection was "dropped".

    For example:

    from flask import Flask
    from time import sleep
    from werkzeug.serving import WSGIRequestHandler
    
    
    app = Flask(__name__)
    
    
    class CustomRequestHandler(WSGIRequestHandler):
    
        def connection_dropped(self, error, environ=None):
            print 'dropped, but it is called at the end of the execution :('
    
    
    @app.route("/")
    def hello():
        for i in xrange(3):
            print i
            sleep(1)
        return "Hello World!"
    
    if __name__ == "__main__":
        app.run(debug=True, request_handler=CustomRequestHandler) 
    

    Maybe you want to investigate a bit more and as your custom request_handler is created when a request comes you can create a thread in the __init__ that checks the status of the connection every second and when it detects that the connection is closed ( check this thread ) then stop the image processing. But I think this is a bit complicated :(.

提交回复
热议问题