Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding scoped sqlalchemy sessions #105

Merged
merged 2 commits into from
Aug 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions conda-store-server/conda_store_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,10 @@ def session_factory(self):

@property
def db(self):
if hasattr(self, "_db"):
return self._db
self._db = self.session_factory()
return self._db
# we are using a scoped_session which always returns the same
# session if within the same thread
# https://docs.sqlalchemy.org/en/14/orm/contextual.html
return self.session_factory()

@property
def configuration(self):
Expand Down
4 changes: 2 additions & 2 deletions conda-store-server/conda_store_server/orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
UniqueConstraint,
ForeignKey,
)
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.orm import sessionmaker, relationship, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine

Expand Down Expand Up @@ -296,5 +296,5 @@ def new_session_factory(url="sqlite:///:memory:", reset=False, **kwargs):

Base.metadata.create_all(engine)

session_factory = sessionmaker(bind=engine)
session_factory = scoped_session(sessionmaker(bind=engine))
return session_factory
7 changes: 7 additions & 0 deletions conda-store-server/conda_store_server/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ def start(self):
app.conda_store = CondaStore(parent=self, log=self.log)
app.authentication = self.authentication_class(parent=self, log=self.log)

@app.after_request
def after_request_function(response):
# force a new session on next request
# since sessions are thread local
app.conda_store.session_factory.remove()
return response

# add dynamic routes
for route, method, func in app.authentication.routes:
app.add_url_rule(route, func.__name__, func, methods=[method])
Expand Down