完成烧瓶中的异步响应

时间:2015-09-06 15:23:52

标签: python asynchronous flask gevent

我正在使用python flask建立一个站点。当它让我感到困惑时,我在这里表明我的糟糕情况:

...  
@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'

如上图所示,后台工作将在后台继续,但我想要的结果应该来自它。

但是,我不知道如何在后台工作正在运行时通知服务器处理其他请求但是有任何结果。

或者是否有任何优雅来放置当前请求,并在后台工作完成时返回响应,在间隔内,服务器可以处理其他请求?

1 个答案:

答案 0 :(得分:0)

客户端和服务器之间的HTTP请求是短暂的,因此不适合您描述的用例。如果服务器在数据准备就绪时将数据发送到客户端,则应使用服务器推送技术。例如,您可以使用Websockets实现客户端和服务器之间的连接。

然而,websockets并不容易管理,因为连接是长时间打开的。 Flask有一些扩展,可以简化websockets的使用。例如,检查https://github.com/kennethreitz/flask-sockets