session - zamaniamin/python GitHub Wiki
The difference between SessionLocal = sessionmaker(bind=engine)
and sessionmaker(autocommit=False, autoflush=False, bind=engine)
lies in the behavior of the created SQLAlchemy sessions, particularly in how they handle transactions and changes.
-
sessionmaker(bind=engine)
:- Sessions created using this configuration have
autocommit=True
by default. autocommit=True
means that each individual database operation (e.g., anINSERT
,UPDATE
, orDELETE
statement) is implicitly wrapped in a transaction, and the transaction is automatically committed after each operation.- This configuration is suitable for read-only operations or situations where you want to commit changes immediately.
- Sessions created using this configuration have
-
sessionmaker(autocommit=False, autoflush=False, bind=engine)
:-
Sessions created using this configuration have
autocommit=False
by default. -
autocommit=False
means that SQLAlchemy will not automatically commit changes to the database. You'll need to explicitly callsession.commit()
to commit any changes made within the session. -
This configuration is suitable for scenarios where you want to control when changes are committed, often used when performing multiple operations that need to be part of a single transaction. It allows you to group multiple database operations into a single transaction and then commit them together, ensuring atomicity.
-
autoflush=False
means that SQLAlchemy will not automatically flush changes to the database. Flushing is the process of synchronizing the in-memory state of objects with the state in the database. Withautoflush=False
, you need to manually callsession.flush()
to synchronize changes. This can be useful in situations where you want more control over when data is written to the database.
-
In summary, the main difference is in how changes are handled:
- With
autocommit=True
, changes are committed automatically after each operation. - With
autocommit=False
, changes need to be committed manually usingsession.commit()
, giving you more control over transaction boundaries.
The choice between these configurations depends on your application's requirements and the specific use case.