I have been learning a little bit about API. I have seen this snippet suggested in the documentation:
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
I’m not sure why is needed. That function is used with the Depends functionality of fast api, and everything works fine. Nonetheless, if I want to write a test and use the db, then I need to do next(get_db()) to get the value. I guess I could also just run SessionLocal(), but I was curious.
>Solution :
See https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/.
It’s Depends‘ way to allow you to do some post-processing when the dependency is being discarded, like closing database connections. A dependency is a simple callable which returns the dependency. What then should be the mechanism to signal back to this callable that the dependency should be "cleaned up"? Well, it’s using Python’s generator mechanism and specifically finally blocks to enable you to add some cleanup code.
You should probably not use get_db directly yourself, but only use it with Depends. Use SessionLocal() directly in this case to get the raw database connection.