[Python] "AttributeError: 'property' object has no attribute 'get'" when using Depends in...

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    To implement authentication for a FastAPI endpoint, I want to make use of the Depends functionality offered in the latest versions (>=0.95) of FastAPI. I have tried several ways to implement it but I am facing an error "AttributeError: 'property' object has no attribute 'get'". This implies that the starlette Request object is not recognised as such when using Depends.

    Endpoint implementation:

    @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!",
    )


    Function authenticate_request checks validity of cookies based on provided Request:

    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")


    This results in error "AttributeError: 'property' object has no attribute 'get'". This implies that the Request object is not passed correctly or is not recognised as such.

    I then tried to solve this without using 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!",
    )


    This is working correctly. If no valid cookie is provided a 401 is returned. Based on this I come to the conclusion that my authenticate_request() function is working correctly.

    Does anybody know why there is a difference in behaviour between Depends() and the alternative solution?

    Help is much appreciated!

    Regards, Laurens

    Continue reading...

Compartilhe esta Página