-
Notifications
You must be signed in to change notification settings - Fork 41
Open
Description
Thanks for this project. I'm evaluating this as a way of managing dependencies in this large flask application I'm refactoring.
How would one manage cleanup of threadlocals, when you have to release things manually. In SQLAlchemy is this required, or anything that uses a threadpool.
I've made a working attempt (based off your example), but I'm not sure if it's the right direction.
class SQLAlchemyModule(Module):
def __init__(self, app):
self.app = app
def configure(self, binder):
db = self.configure_db()
binder.bind(Session, to=self.create_session, scope=request_scope)
def configure_db(self):
connection_string = (
'postgresql+psycopg2://{user}@{host}/{db}'
).format(
user=self.app.config['PGSQL_USER'],
host=self.app.config['PGSQL_HOST'],
db=self.app.config['PGSQL_DB'],
)
self.engine = create_engine(
connection_string,
convert_unicode=True,
)
self.Session = scoped_session(sessionmaker(bind=self.engine))
self.app.teardown_request(cleanup_session)
def create_session(self) -> Session:
return self.Session()
def destroy_session(self, *args):
self.Session.remove()
Is there anything I could do to make this class more idiomatic with Injector?
What I think would be really lovely, instead of binding to a function, you could bind to something with a yield statement.
So create_session would become
@contextmanager
def create_session(self) -> Session:
try:
yield self.Session()
finally:
self.Session.close()
Metadata
Metadata
Assignees
Labels
No labels