Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do we need to use a generator when creating a connection to the database in fast api

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading