[파이썬] SQLAlchemy 커스텀 Session Extension

SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides an easy-to-use and flexible way to interact with databases. One of the key features of SQLAlchemy is the concept of sessions, which represents a transactional scope over database operations.

In this blog post, we will explore how to create a custom session extension in SQLAlchemy. A session extension allows us to add custom behavior to the session, such as automatically updating timestamp fields or logging database operations.

Let’s start by setting up a basic SQLAlchemy session:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Set up database connection
engine = create_engine("sqlite:///mydatabase.db")
Session = sessionmaker(bind=engine)
session = Session()

To create a custom session extension, we need to define a class that inherits from sqlalchemy.orm.SessionExtension. This class must implement a set of methods that will be called during various stages of the session’s lifecycle.

Here is an example of a custom session extension that logs all the database operations:

from sqlalchemy.orm.session import SessionExtension

class LoggingSessionExtension(SessionExtension):
    def before_flush(self, session, flush_context, instances):
        for operation in session.dirty:
            print(f"Updated instance: {operation}")
        for operation in session.new:
            print(f"New instance: {operation}")
        for operation in session.deleted:
            print(f"Deleted instance: {operation}")

In this example, the before_flush method is overridden to print the details of updated, new, and deleted instances before they are flushed to the database.

To use this custom session extension, we need to register it with the session:

session.extension = LoggingSessionExtension()

Now, whenever we perform database operations using the session, the custom session extension will be invoked, and the details will be logged.

# Create a new object
my_object = MyObject(name="Test")
session.add(my_object)
session.commit()

# Update an existing object
my_object.name = "Updated Test"
session.commit()

# Delete an object
session.delete(my_object)
session.commit()

When running the code above, we will see the details of the database operations logged to the console.

Creating a custom session extension allows us to add additional functionality to the SQLAlchemy session. We can modify data, track changes, enforce business logic, or perform any other custom behavior based on our requirements.

In conclusion, SQLAlchemy provides a flexible way to create custom session extensions to enhance the functionality of our applications. By leveraging the power of session extensions, we can easily implement complex and custom database operations in our SQLAlchemy-based projects.