From bea38d67df094609b9d21ebe1131193d6c269e76 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Sun, 13 Jun 2021 16:53:36 -0700 Subject: [PATCH] Allow greenlet scoping for sessions --- amanuensis/db/database.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/amanuensis/db/database.py b/amanuensis/db/database.py index 254a488..0fb68f3 100644 --- a/amanuensis/db/database.py +++ b/amanuensis/db/database.py @@ -3,8 +3,12 @@ Database connection setup """ from sqlalchemy import create_engine, MetaData, event from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import scoped_session -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import scoped_session, sessionmaker + +try: + from greenlet import getcurrent as get_ident +except ImportError: + from threading import get_ident # Define naming conventions for generated constraints @@ -34,7 +38,9 @@ class DbContext: cursor.close() # Create a thread-safe session factory - self.session = scoped_session(sessionmaker(bind=self.engine)) + self.session = scoped_session( + sessionmaker(bind=self.engine), scopefunc=get_ident + ) def __call__(self, *args, **kwargs): """Provides shortcut access to session.execute."""