Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use yield to get Sessionlocal in Fastapi with sqlalchemy?

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?

like image 358
Ujesh Nada Avatar asked Nov 10 '20 06:11

Ujesh Nada


People also ask

Does FastAPI use SQLAlchemy?

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.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

What is Orm_mode?

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

What is Sessionmaker in SQLAlchemy?

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.


2 Answers

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.

enter image description here

So what do we have in this example?

  • A connection pool that holds 5 different connections.
  • 2 endpoint
  • 3 incoming requests.

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.

like image 194
Yagiz Degirmenci Avatar answered Oct 26 '22 06:10

Yagiz Degirmenci


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 a try statement with a finally clause, that finally 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.

like image 38
alex_noname Avatar answered Oct 26 '22 06:10

alex_noname