You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Litestar访问GET /报AttributeError: coroutine无to_asgi_response属性

Litestar应用访问根路径触发AttributeError错误

问题描述

执行启动命令:

poetry run litestar --app 'litestar_app.app:app' run --reload --debug

应用正常启动,但访问http://127.0.0.1:8000时出现以下错误:

AttributeError on GET /
'coroutine' object has no attribute 'to_asgi_response'
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\handlers\http_handlers\_utils.py in handler at line 152
    async def handler(
        data: Response,
        app: Litestar,
        request: Request,
        **kwargs: Any,  # kwargs is for return dto
    ) -> ASGIApp:
        response = await after_request(data) if after_request else data  # type:ignore[arg-type,misc]
        return response.to_asgi_response(  # type: ignore
            app=None,
            background=background,
            cookies=cookie_list,
            headers=normalized_headers,
            media_type=media_type,
            request=request,
            status_code=status_code,
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\handlers\http_handlers\base.py in get.to_response at line 528
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\routes\http.py in HTTPRoute._call_handler_function at line 158
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\routes\http.py in HTTPRoute._get_response_for_request at line 134
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\routes\http.py in HTTPRoute.handle at line 82
↓ C:\Users\UserName\AppData\Local\pypoetry\Cache\virtualenvs\pythonex-app-U7JqGUH_-py3.11\Lib\site-packages\litestar\middleware\exceptions\middleware.py in ExceptionHandlerMiddleware.__call__ at line 192

应用核心配置代码(app.py)

from litestar import Litestar
from .config.compression import compression_config
from .config.template import template_config
from .config.static_files import static_files_config
from .controllers.index import IndexController
from .controllers.api.users import UsersController
from litestar.config.cors import CORSConfig
from pythonex_app.config.app import app_config

# 本地运行时允许所有跨域请求,生产环境关闭
cors_config = CORSConfig() if app_config.ENV == "LOCAL" else None

app = Litestar(
    route_handlers=[IndexController, UsersController],
    middleware=[],
    compression_config=compression_config,
    template_config=template_config,
    static_files_config=static_files_config,
    cors_config=cors_config,
)

错误原因分析

这个错误的核心是请求处理函数返回了未被等待的协程对象,而Litestar无法直接将协程转换为ASGI响应。问题大概率出在IndexController中处理根路径(GET /)的方法里:

  • 要么是异步方法中调用了其他异步函数但未加await,直接返回了协程;
  • 要么是误将协程对象作为响应返回,而非合法的响应实例(比如TemplateResponse、JSONResponse等)。

解决方法

  1. 打开IndexController文件,找到处理GET /的方法(通常是get方法)
  2. 检查方法的实现:
    • 如果是异步方法(带async关键字),确保所有异步操作都加上await,并且返回合法响应对象:
      # 错误写法:直接返回未等待的协程
      async def get(self):
          return render_template("index.html")  # render_template是异步函数但未await
      
      # 正确写法
      async def get(self) -> TemplateResponse:
          # 等待异步操作完成
          await some_async_operation()
          # 返回TemplateResponse实例
          return TemplateResponse(template_name="index.html", context={"key": "value"})
      
    • 如果不需要异步操作,直接定义为同步方法,返回响应对象即可:
      def get(self) -> TemplateResponse:
          return TemplateResponse(template_name="index.html", context={"key": "value"})
      

内容的提问来源于stack exchange,提问作者Asghar C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 03:11:03