FastAPI路由报错:TypeError: root()缺少必需参数'request'
解决FastAPI中TypeError: root() missing 1 required positional argument: 'request'错误
错误根源是你误用了Flask风格的@app.route装饰器,FastAPI不支持这种写法。它依赖自身的HTTP方法装饰器(如@app.get、@app.post等)来处理Request对象的自动注入逻辑,用错装饰器会导致Request参数无法被正确传递,从而触发报错。
修正后的代码如下:
from fastapi import FastAPI, Request app = FastAPI() # 使用FastAPI的GET方法装饰器,若需支持其他HTTP方法,可替换为对应装饰器 @app.get("/{full_path:path}") async def root(full_path: str, request: Request): print(request.method, full_path) return "HIYO"
如果需要匹配所有HTTP方法,可以用api_route装饰器:
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"]) async def root(full_path: str, request: Request): print(request.method, full_path) return "HIYO"
内容的提问来源于stack exchange,提问作者Tangles
相关产品推荐
相关产品推荐

