Search code examples
pythonasynchronousflaskgevent

accomplish asynchronized response in flask


I'm setting up a site using python flask. When it confuses me, I am here to show my poor situation:

...  
@app.route('/wanted_delay_response')
def delay_response():
    def background_work():
        # I want to check some flags in the background
        # this should not block, but it does as I try below
        pass
    gevent.spawn(background_work)
    # the most confusing part comes:
    return 'This is not what I really want to response'

as shown above, the background work will continue in the background, but the result I want should come from it.

However, I have no idea how to notify the server to treat other request when the background work is running but yet with any result.

Or is there any elegant to lay aside the current request, and come back to response when background work finishes, within the interval, the server can treat other requests?


Solution

  • HTTP requests between client and server are short-lived and therefore not suitable for the use-case you described. In the case where server sends data to client when the data is ready, use should use server push technology. For example you can use Websockets to implement the connection between client and server.

    However websockets are not that easy to manage, because connections are open for long periods. There are some extensions for Flask, which could simplify the use of websockets. For example check https://github.com/kennethreitz/flask-sockets.