python type_error ai_generated true

AssertionError: Route function must be async

ID: python/starlette-missing-route-handler

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-09-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. Adding @app.route without async 90% fail

    Starlette requires async handlers; sync functions cause assertion errors.

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

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