pypidependency-injection95% confidence\u2191 26

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

Full error message
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.

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.

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/f8adedd470097594996c529b5311d6089ce73f8af89f2d3dc1c4856e1a7e3bc8
hash \u00b7 f8adedd470097594996c529b5311d6089ce73f8af89f2d3dc1c4856e1a7e3bc8
AttributeError: 'Depends' object has no attribute &#… — DepScope fix | DepScope