Non-Message Queue / Simple Long-Polling in Python (and Flask)

后端 未结 2 801
故里飘歌
故里飘歌 2021-01-30 07:21

I am looking for a simple (i.e., not one that requires me to setup a separate server to handle a messaging queue) way to do long-polling for a small web-interface that runs calc

2条回答
  •  失恋的感觉
    2021-01-30 08:11

    Long-polling was a reasonable work-around before simple, natural support for Web Sockets came to most browsers, and before it was easily integrated alongside Flask apps. But here in mid-2013, Web Socket support has come a long way.

    Here is an example, similar to the one above, but integrating Flask and Web Sockets. It runs atop server components from gevent and gevent-websocket.

    Note this example is not intended to be a Web Socket masterpiece. It retains a lot of the lpoll structure, to make them more easily comparable. But it immediately improves responsiveness, server overhead, and interactivity of the Web app.

    Update for Python 3.7+

    5 years since the original answer, WebSocket has become easier to implement. As of Python 3.7, asynchronous operations have matured into mainstream usefulness. Python web apps are the perfect use case. They can now use async just as JavaScript and Node.js have, leaving behind some of the quirks and complexities of "concurrency on the side." In particular, check out Quart. It retains Flask's API and compatibility with a number of Flask extensions, but is async-enabled. A key side-effect is that WebSocket connections can be gracefully handled side-by-side with HTTP connections. E.g.:

    from quart import Quart, websocket
    
    app = Quart(__name__)
    
    @app.route('/')
    async def hello():
        return 'hello'
    
    @app.websocket('/ws')
    async def ws():
        while True:
            await websocket.send('hello')
    
    app.run()
    

    Quart is just one of the many great reasons to upgrade to Python 3.7.

提交回复
热议问题