python type_error ai_generated true

断言错误:路由函数必须是异步的

AssertionError: Route function must be async

ID: python/starlette-missing-route-handler

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

版本兼容性

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

根因分析

Starlette中的路由处理器被定义为同步函数而不是异步函数。

English

A route handler in Starlette is defined as a synchronous function instead of async.

generic

解决方案

  1. 95% 成功率 Define the route handler as async
    @app.route('/')
    async def homepage(request):
        return PlainTextResponse('Hello')
  2. 50% 成功率 Use a sync wrapper if absolutely necessary
    from starlette.responses import PlainTextResponse
    @app.route('/')
    def sync_homepage(request):
        return PlainTextResponse('Hello')

无效尝试

常见但无效的做法:

  1. Adding @app.route without async 90% 失败

    Starlette requires async handlers; sync functions cause assertion errors.

  2. Wrapping the function in a decorator that makes it async 70% 失败

    Complex and may not work correctly with Starlette's internals.