Created
August 14, 2023 17:49
-
-
Save mglowinski93/07a36843ec7cc31d26538c11305a8d51 to your computer and use it in GitHub Desktop.
Asynchronous sqlalchemy with explicit engine passed as parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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