Python Transaction Management

5.1 · active · verified Sun Apr 12

The `transaction` package provides a generic transaction implementation for Python, offering a two-phase commit protocol. It allows multiple backends (such as ZODB, SQLAlchemy, filesystem, or custom data managers) to participate in a single transaction, ensuring atomicity across diverse storage systems. It also supports savepoints, enabling partial rollbacks. The current version is 5.1, with a release cadence that has seen several major updates over the last few years, maintaining active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic pattern of using `transaction.commit()` and `transaction.abort()` within a try-except block. In a practical scenario, `some_backend_operation()` would involve one or more data managers (e.g., from ZODB, SQLAlchemy, or a custom implementation) that register themselves with the global transaction manager when modifications are made. The `transaction` library coordinates these data managers to ensure an all-or-nothing outcome using a two-phase commit protocol.

import transaction

# In a real application, 'some_backend_operation()' would interact
# with a data manager (e.g., ZODB, SQLAlchemy session, or a custom one)
# which registers itself with the transaction machinery automatically
# or explicitly.
# For this example, we'll simulate a backend operation.

def some_backend_operation(success=True):
    print(f"Performing backend operation (success={success})...")
    # In a real scenario, this would be where changes are made
    # to a persistent store via a registered data manager.
    if not success:
        raise ValueError("Simulated backend error!")
    print("Backend operation completed.")

try:
    # Code block where operations participating in the transaction occur
    some_backend_operation(success=True)
    # If multiple backends are involved, their operations would be here too
    # e.g., db_session.add(some_object), file_manager.write_data()

    # Commit the transaction if all operations succeed
    print("Attempting to commit transaction...")
    transaction.commit()
    print("Transaction committed successfully.")
except ValueError as e:
    # Rollback the transaction if any operation fails
    print(f"Error: {e}. Rolling back transaction...")
    transaction.abort()
    print("Transaction aborted.")
except Exception as e:
    print(f"Unexpected error: {e}. Aborting transaction...")
    transaction.abort()

view raw JSON →