Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'Depends' object has no attribute 'query' FastAPI

So I am trying to write simple function here, but every time I run swagger, I got above mentioned error.

Here's my function:

def authenticate_user(username: str, password: str, db: Session = Depends(bd.get_db)):
    user = db.query(bd.User.username).filter(username == username).first()
    if not user:
        return False
    if not verify_password(password, user.password_hash):
        return False
    return user

and here's my get_db function it is pretty standard:

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

I've noticed that Depends(bd.get_db) works perfectly fine within endpoint functions (the ones with @app.post/@app.get decorators), but somehow doesn't work within plain functions.

Apparently, I don't quite understand the concept of dependency injections, but I can't quite grasp it yet.

like image 593
TobaSko Avatar asked Sep 10 '25 14:09

TobaSko


1 Answers

This page helped me a lot, https://github.com/tiangolo/fastapi/issues/1693#issuecomment-665833384

you can't use Depends in your own functions, it has to be in FastAPI functions, mainly routes. You can, however, use Depends in your own functions when that function is also a dependency, so could can have a chain of functions.

Eg, a route uses Depends to resolve a 'getcurrentuser', which also uses Depends to resolve 'getdb', and the whole chain will be resolved. But if you then call 'getcurrentuser' without using Depends, it won't be able to resolve 'getdb'.

What I do is get the DB session from the route and then pass it down through every layer and function. I believe this is also better design.

like image 150
Zhou Hongbo Avatar answered Sep 13 '25 05:09

Zhou Hongbo