asyncio.sleep()在Uvicorn和Starlette中等待时被取消,但在其他情况下可以正常工作。
创始人
2024-09-21 05:30:39
0

这是因为在Uvicorn和Starlette中,当一个HTTP请求被取消时,它会中断正在进行的所有协程。因此,在使用asyncio.sleep()等待时,如果请求被取消,协程将被中断,从而导致asyncio.sleep()立即停止并抛出CancelledError。

要解决这个问题,可以将asyncio.sleep()包装在try/except块中,以捕获CancelledError并返回。以下示例演示了如何包装asyncio.sleep()以使其在Uvicorn和Starlette中正常工作。

import asyncio
from starlette.applications import Starlette
from starlette.responses import JSONResponse


async def long_running_task():
    try:
        await asyncio.sleep(10)
        return {"status": "done"}
    except asyncio.CancelledError:
        return {"status": "cancelled"}


app = Starlette()


@app.route("/")
async def homepage(request):
    task = asyncio.ensure_future(long_running_task())

    while not task.done():
        await asyncio.sleep(0)

    return JSONResponse(task.result())

在上面的示例中,我们将asyncio.sleep()包装在try/except块中以捕获CancelledError,并返回“cancelled”状态。这将确保即使请求被取消,也不会中断协程并导致asyncio.sleep()被取消。

相关内容

热门资讯

开挂辅助下载"wep... wepoker怎么拿到好牌是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户...
开挂辅助神器"wep... 开挂辅助神器"wepoker辅助器安装包"开挂(透视)辅助工具(有挂分享);无需打开直接搜索打开薇:...
开挂辅助平台"we-... 开挂辅助平台"we-poker软件"开挂(透视)辅助神器(有挂总结)we-poker软件ai黑科技系...
开挂辅助工具"hhp... 开挂辅助工具"hhpoker怎么破解"开挂(透视)辅助插件(有挂方针);无需打开直接搜索微信(136...
开挂辅助安装"wep... 开挂辅助安装"wepoker手机插件"开挂(透视)辅助工具(有挂技术);无需打开直接搜索打开薇:13...
开挂辅助插件"wep... 开挂辅助插件"wepoker辅助是真的吗"开挂(透视)辅助安装(有挂秘籍) 了解更多开挂安装加(13...
开挂辅助安装"pok... 开挂辅助安装"pokemmo手机版脚本"开挂(透视)辅助插件(有挂存在);无需打开直接搜索加(薇:1...
开挂辅助下载"约局吧... 开挂辅助下载"约局吧怎么看有没有挂"开挂(透视)辅助平台(有挂讲解)>>您好:软件加13670430...
开挂辅助软件"wpk... 开挂辅助软件"wpk刷入池率脚本"开挂(透视)辅助软件(有挂方法);无需打开直接搜索加(薇:1367...
开挂辅助下载"wep... wepoker透视脚本下载是一款专注玩家量身打造的游戏记牌类型软件,在wepoker透视脚本下载这款...