Skip to content

Instantly share code, notes, and snippets.

@mglowinski93
Created August 14, 2023 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mglowinski93/07a36843ec7cc31d26538c11305a8d51 to your computer and use it in GitHub Desktop.
Save mglowinski93/07a36843ec7cc31d26538c11305a8d51 to your computer and use it in GitHub Desktop.
Asynchronous sqlalchemy with explicit engine passed as parameter
from contextlib import asynccontextmanager
from enum import Enum
from sqlalchemy import (
Column,
Integer,
String,
)
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncEngine
from sqlalchemy.orm import declarative_base
class Engines(Enum):
PRIMARY = create_async_engine(
url="<your_connection_string>",
echo=True,
)
SECONDARY = create_async_engine(
url="<your_connection_string>",
echo=True,
)
Base = declarative_base()
class Tutorial(Base):
__tablename__ = "tutorials"
tutorial_id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False)
def async_session_generator(engine: AsyncEngine):
return async_sessionmaker(bind=engine)
@asynccontextmanager
async def get_session(engine: Engines = Engines.PRIMARY):
try:
async_session = async_session_generator(engine=engine.value)
async with async_session() as session:
yield session
except:
await session.rollback()
raise
finally:
await session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment