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.

  1. sessionmaker(bind=engine):

    • Sessions created using this configuration have autocommit=True by default.
    • autocommit=True means that each individual database operation (e.g., an INSERT, UPDATE, or DELETE 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.
  2. 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 call session.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. With autoflush=False, you need to manually call session.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 using session.commit(), giving you more control over transaction boundaries.

The choice between these configurations depends on your application's requirements and the specific use case.