def get_db():
db = SessionLocal()
try:
return db
finally:
db.close()
I got this code snipped to get Sessionlocal in fastapi with Sqlalchemy. Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield. Can someone help me?
FastAPI easily integrates with SQLAlchemy and SQLAlchemy supports PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server and others. Other python microservice frameworks like Flask don't integrate with SQLAlchemy easily. It is common to use Flask with a package called Flask-SQLAlchemy.
_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.
orm_mode = True. It doesn't use : as for the type declarations before. This is setting a config value, not declaring a type. Pydantic's orm_mode will tell the Pydantic model to read the data even if it is not a dict , but an ORM model (or any other arbitrary object with attributes).
Python Flask and SQLAlchemy ORM In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy.
Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield.
It's a great question, the answer is, yes there's a reason to use yield instead of return.
SQLAlchemy has a Connection Pooling mechanism by default. That means with yield you are creating a single session for each request. When you use return
you are using a single database connection for all your app.
Isn't it clear? Let's visualize it to make things more interesting.
So what do we have in this example?
When you use yield it would look something like this underneath because it goes to an endpoint, asks something to the database and yield creates a new Session object every time. It provides a transactional scope around a series of operations, but using return
there instead of yield
will just return that session object.
There is a fundamental difference, when you use a return
, the closing is performed before the function returns the db
object, in fact you are returning a closed db
object. Because
When
return
passes control out of atry
statement with afinally
clause, thatfinally
clause is executed before really leaving the function.
Otherwise, when the yield
is used, the finally
code block is executed after the request has been processed and the response has been sent. You can read more about dependencies with yield here.
Why your code continues to work, I cannot tell without seeing the whole code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With