[파이썬] SQLAlchemy 연결된 세션 관리

SQLAlchemy is a popular Object-Relational Mapping (ORM) library for Python. It provides a high-level interface for connecting to and interacting with databases. In this blog post, we will explore the concept of session management in SQLAlchemy.

What is a Session?

A session in SQLAlchemy represents a transactional scope where database operations can be performed. Sessions provide a way to maintain a persistent connection to the database and manage the lifecycle of objects mapped to tables.

Connecting to the Database

Before we can create and manage sessions, we need to establish a connection to the database. SQLAlchemy supports various database engines such as MySQL, PostgreSQL, SQLite, and more. Let’s assume we are using PostgreSQL for this example.

from sqlalchemy import create_engine

engine = create_engine('postgresql://username:password@localhost/database')

Here, we create an engine object using the create_engine function and pass the connection URL for our PostgreSQL database. Replace username, password, localhost, and database with your actual database credentials.

Creating a Session

With the database connection established, we can now create a session object using the sessionmaker function. This function takes the engine as an argument and returns a session class.

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)

Now, we can create individual sessions whenever we need to interact with the database. It is recommended to create only a single session per request or operation for better performance.

Usage of Sessions

To use a session, we instantiate it from the Session class we created earlier. SQLAlchemy provides a contextmanager called contextmanager for handling sessions in a safe and efficient way.

from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager

Session = sessionmaker(bind=engine)

@contextmanager
def get_session():
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

In the above code, we define a contextmanager function called get_session using the contextmanager decorator. This function creates a session, yields it to the calling code block, performs a commit if no exception occurs, rolls back the transaction otherwise, and finally closes the session.

Using the Session

Let’s see an example of how we can use the session to perform database operations using SQLAlchemy’s ORM.

from models import User
from get_session import get_session

def create_user(username, email):
    with get_session() as session:
        user = User(username=username, email=email)
        session.add(user)

def get_user(username):
    with get_session() as session:
        user = session.query(User).filter_by(username=username).first()
        return user

In the above code, we have two functions: create_user and get_user. These functions use the get_session contextmanager to create and manage sessions automatically.

By using sessions, we can encapsulate database operations into logical units and ensure data integrity through transactions.

Conclusion

Session management is a crucial aspect of working with SQLAlchemy. It allows us to connect to the database, perform operations, and manage transactions efficiently. With the contextmanager decorator, we can safely and conveniently handle sessions within our code.

Remember to commit the session if the operations are successful, and rollback if an error occurs. Finally, always close the session to release the resources.

SQLAlchemy’s session management simplifies database operations and enhances the reliability of our Python applications.