Database Session Creation with SQLAlchemy Check

  • Share this:

Code introduction


This function creates a database session using SQLAlchemy's sessionmaker and checks if the database exists. If the database does not exist, it creates the database.


Technology Stack : SQLAlchemy, SQLAlchemy-Utils

Code Type : Database Session Management

Code Difficulty : Intermediate


                
                    
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

def create_db_session(engine_name='default'):
    """
    This function creates a database session using SQLAlchemy's sessionmaker and checks if the database exists.
    If the database does not exist, it creates the database.

    :param engine_name: The name of the SQLAlchemy engine to use.
    :return: A database session.
    """
    # Create a sessionmaker instance
    Session = sessionmaker(bind=engine_name)
    
    # Check if the database exists
    if not database_exists(bind=engine_name):
        # Create the database if it does not exist
        create_database(bind=engine_name)
    
    # Return a new database session
    return Session()