python config_error ai_generated true

运行时错误:不支持生命周期协议。请使用 'lifespan' 参数。

RuntimeError: Lifespan protocol not supported. Use 'lifespan' parameter.

ID: python/starlette-missing-lifespan

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-05-10首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

Starlette 应用程序在使用异步上下文管理器处理启动/关闭时需要设置 lifespan 参数。

English

Starlette applications require the lifespan parameter to be set when using async context managers for startup/shutdown.

generic

解决方案

  1. 95% 成功率 Define a lifespan context manager
    from contextlib import asynccontextmanager
    
    @asynccontextmanager
    async def lifespan(app):
        # startup
        yield
        # shutdown
    
    app = Starlette(lifespan=lifespan)
  2. 90% 成功率 Use on_startup and on_shutdown callbacks
    app = Starlette(on_startup=[startup_func], on_shutdown=[shutdown_func])

无效尝试

常见但无效的做法:

  1. Not using any lifespan parameter 100% 失败

    The application expects explicit lifespan handling.

  2. Setting lifespan to a string like 'auto' 90% 失败

    The lifespan parameter must be a callable or None.