SQLAlchemy

Multithreading

Typically, SQLAlchemy does not support multithreading. This can be an issue if your API/web client uses multiple workers. However, we can support multithreading as follows:

## This is a global util file

import os
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from api.config import db_username, db_password, db_private_ip, db_database_name

DB_CREDENTIALS = f"{db_username}:{db_password}@{db_private_ip}:3306/{db_database_name}"

def create_engine_and_session():
      # Ensure pymysql is installed
    db_uri = f"mysql+pymysql://{DB_CREDENTIALS}"

    new_engine = create_engine(db_uri, echo=False)
    new_session = sessionmaker(autocommit=False,
                               autoflush=False,
                               bind=new_engine)

    return new_engine, new_session

current_engine, Session = create_engine_and_session()

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

Enums

Base Class

When each SQLAlchemy model/table class has common methods, we can put them in the Base class that all the tables inherit from.

Here are some methods I found to be useful:

Foreign Keys

Datetime/Timestamp Column

Useful SQLAlchemy Utility Functions

Last updated

Was this helpful?