Reputation: 599
If I want to use database while processing a request, I make a Dependency Injection like this:
@app.post("/sample_test")
async def sample_test(db: Session = Depends(get_db)):
return db.query(models.User.height).all()
But I cannot do it with events like this:
@app.on_event("startup")
async def sample_test(db: Session = Depends(get_db)):
return db.query(models.User.height).all()
because starlette
events don't support Depends.
This is my get_db()
function:
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
just like in FastAPI manual (https://fastapi.tiangolo.com/tutorial/sql-databases/).
How can I access get_db()
inside my event function, so I can work with a Session?
I've tried:
@app.on_event("startup")
async def sample_test(db: Session = Depends(get_db)):
db = next(get_db())
return db.query(models.User.height).all()
but it doesn't work.
I use MSSQL, if it's important.
Upvotes: 5
Views: 1748
Reputation: 15162
Instead of using a dependency you can import the SessionLocal
you've created as shown in the FastAPI manual and use a contextmanager to open and close this session:
@app.on_event("startup")
async def sample_test():
with SessionLocal() as db:
return db.query(models.User.height).all()
Upvotes: 4