from apistar import Component from sqlalchemy.engine import Engine from sqlalchemy.orm import Session from sqlalchemy.orm import sessionmaker, Session, scoped_session DBSession = scoped_session(sessionmaker()) class SQLAlchemySession(Component): def __init__(self, engine=None): if not isinstance(engine, Engine): raise ValueError('SQLAlchemySession must be instantiated with a sqlalchemy.engine.Engine object') self.engine = engine DBSession.configure(bind=self.engine) def resolve(self) -> Session: return DBSession()