python network_error ai_generated true

Starlette HTTP 异常:404 未找到。

starlette.exceptions.HTTPException: 404 Not Found

ID: python/starlette-http-exception-not-found

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

版本兼容性

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

根因分析

请求的 URL 与 Starlette 应用中的任何路由不匹配。

English

Requested URL does not match any route in the Starlette application.

generic

解决方案

  1. 90% 成功率
    from starlette.applications import Starlette
    from starlette.routing import Route
    
    async def homepage(request):
        return Response('Hello')
    
    routes = [Route('/', homepage)]
    app = Starlette(routes=routes)
    # Ensure route paths are correct with trailing slashes
  2. 85% 成功率
    Add a custom 404 handler: 
    from starlette.exceptions import HTTPException
    from starlette.responses import JSONResponse
    
    async def not_found(request, exc):
        return JSONResponse(status_code=404, content={"message": "Not Found"})
    
    app.add_exception_handler(HTTPException, not_found)

无效尝试

常见但无效的做法:

  1. 75% 失败

    Catch-all routes may shadow specific routes if defined first.

  2. 60% 失败

    Middleware cannot easily modify response status; may cause recursion.