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

FastAPI使用Depends时出现AttributeError错误求助

FastAPI Depends使用时出现AttributeError的问题解决

问题场景

在FastAPI(版本>=0.95)中尝试用Depends实现接口认证,运行时报错:AttributeError: 'property' object has no attribute 'get',提示Request对象未被正确识别。两种实现方式行为不一致:使用Depends的版本报错,直接传入Request的版本正常运行。

报错的Depends实现代码

@app.get("/")
async def home(user: Annotated[User, Depends(authenticate_request(Request))]):
    """
    status _summary_
    Returns status message if service is running
    """
    if isinstance(user, User):
        return {"Welcome, service is running ok!"}
    raise HTTPException(
        status_code=401,
        detail="User not authorized!",
    )

认证函数代码

def authenticate_request(request: Request) -> User:
    cookie1 = request.cookies.get("x")
    cookie2 = request.cookies.get("y")
    if cookie1 is not None and cookie2 is not None:
        tenant = get_tenant(request)
        if user := authenticate_cookies(cookie1, cookie2, tenant):
            if not tenant.startswith(user.tenant):
                print("Unauthorized: Token hostname mismatch")
                raise Exception("Token hostname mismatch")
            return user
    print("Unauthorized: please login")
    raise HTTPException(status_code=401, detail="Unauthorized: please login")

正常运行的非Depends实现代码

@app.get("/")
async def home(request: Request):
    """
    status _summary_
    Returns status message if service is running
    """
    user = authenticate_request(request=request)
    if isinstance(user, User):
        return {"Welcome, service is running ok!"}
    raise HTTPException(
        status_code=401,
        detail="User not authorized!",
    )

问题原因

错误核心在于Depends(authenticate_request(Request))这一行:你直接将Request类作为参数传入authenticate_request函数,而非让FastAPI自动注入当前请求的Request实例。

此时authenticate_request函数接收的request参数是Request类本身,而非请求实例。Request类的cookies是一个类属性(property),不是字典结构,调用.get()方法自然会抛出AttributeError。

而正常运行的代码中,直接接收FastAPI注入的Request实例再传给认证函数,因此能正确获取cookies字典。

修正方案

将Depends的参数改为直接传入authenticate_request函数本身,FastAPI会自动识别函数的参数(这里是Request),并注入对应的请求实例:

@app.get("/")
async def home(user: Annotated[User, Depends(authenticate_request)]):
    """
    status _summary_
    Returns status message if service is running
    """
    if isinstance(user, User):
        return {"Welcome, service is running ok!"}
    raise HTTPException(
        status_code=401,
        detail="User not authorized!",
    )

修改后,FastAPI会在处理请求时自动把当前Request实例传给authenticate_request函数,函数就能正常调用request.cookies.get()完成认证逻辑。

内容的提问来源于stack exchange,提问作者Laurens Fleuren

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:52:02