使用websockets正常关闭uvicorn starlette应用程序

时间:2019-09-27 11:30:20

标签: python python-asyncio asgi starlette uvicorn

鉴于此示例Starlette应用具有打开的websocket连接,您如何关闭Starlette应用?我正在使用uvicorn。每当我按Ctrl+C时,输出就是Waiting for background tasks to complete.,它会永远挂起。

from starlette.applications import Starlette

app = Starlette()

@app.websocket_route('/ws')
async def ws(websocket):
    await websocket.accept()

    while True:
        # How to interrupt this while loop on the shutdown event?
        await asyncio.sleep(0.1)

    await websocket.close()

我尝试在关闭事件上切换bool变量,但该变量从未更新。它始终是False

例如

app.state.is_shutting_down = False


@app.on_event('shutdown')
async def shutdown():
    app.state.is_shutting_down = True


@app.websocket_route('/ws')
async def ws(websocket):
    await websocket.accept()

    while app.state.is_shutting_down is False:

2 个答案:

答案 0 :(得分:3)

您的变量未更改的原因是,在所有任务执行完毕(即无限循环)之后,将执行“关机”事件的处理程序。

在asyncio事件循环上设置信号处理程序可能无法正常工作,因为我认为uvicorn已经为其自身的关机过程设置了单个信号处理程序。
相反,您可以使用Monkey Patch uvicorn信号处理程序来检测应用程序关闭并在该新函数中设置控制变量。

import asyncio
from starlette.applications import Starlette
from uvicorn.main import Server

original_handler = Server.handle_exit

class AppStatus:
    should_exit = False

    @staticmethod
    def handle_exit(*args, **kwargs):
        AppStatus.should_exit = True
        original_handler(*args, **kwargs)

Server.handle_exit = AppStatus.handle_exit

app = Starlette()

@app.websocket_route('/ws')
async def ws(websocket):
    await websocket.accept()

    while AppStatus.should_exit is False:

        await asyncio.sleep(0.1)

    await websocket.close()
    print('Exited!')

答案 1 :(得分:0)

我真的无法重现问题,我明白了

INFO: Started server process [31]
INFO: Waiting for application startup.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
^CINFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Finished server process [31]

但是我在自己的异步应用程序中要正常关闭的是:

import signal

async def shutdown(signal: signal):
    """
    try to shut down gracefully
    """
    logger.info("Received exit signal %s...", signal.name)
    tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
    [task.cancel() for task in tasks]
    logging.info("Canceling outstanding tasks")
    await asyncio.gather(*tasks)


if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
    for s in signals:
        loop.add_signal_handler(
            s, lambda s=s: asyncio.create_task(shutdown(s))
        )

您可能必须将await websocket.close()移至shutdown方法中。