diff --git a/server/szurubooru/db/session.py b/server/szurubooru/db/session.py index 98ad150b..3fb1fb98 100644 --- a/server/szurubooru/db/session.py +++ b/server/szurubooru/db/session.py @@ -1,29 +1,27 @@ +import threading import sqlalchemy from szurubooru import config -class QueryCounter(object): - _query_count = 0 - - @staticmethod - def bump(): - QueryCounter._query_count += 1 - - @staticmethod - def reset(): - QueryCounter._query_count = 0 - - @staticmethod - def get(): - return QueryCounter._query_count - - # pylint: disable=invalid-name _engine = sqlalchemy.create_engine(config.config['database']) sessionmaker = sqlalchemy.orm.sessionmaker(bind=_engine) session = sqlalchemy.orm.scoped_session(sessionmaker) -reset_query_count = QueryCounter.reset -get_query_count = QueryCounter.get + +_data = threading.local() + + +def reset_query_count(): + _data.query_count = 0 + + +def get_query_count(): + return _data.query_count + + +def _bump_query_count(): + _data.query_count = getattr(_data, 'query_count', 0) + 1 + sqlalchemy.event.listen( - _engine, 'after_execute', lambda *args: QueryCounter.bump()) + _engine, 'after_execute', lambda *args: _bump_query_count()) diff --git a/server/szurubooru/middleware/db_session.py b/server/szurubooru/middleware/db_session.py index 8f8a1a55..4a2fe960 100644 --- a/server/szurubooru/middleware/db_session.py +++ b/server/szurubooru/middleware/db_session.py @@ -5,7 +5,6 @@ from szurubooru.rest import middleware @middleware.pre_hook def _process_request(ctx): ctx.session = db.session() - db.reset_query_count() @middleware.post_hook diff --git a/server/szurubooru/middleware/request_logger.py b/server/szurubooru/middleware/request_logger.py index c430ca4e..47b43ab5 100644 --- a/server/szurubooru/middleware/request_logger.py +++ b/server/szurubooru/middleware/request_logger.py @@ -6,6 +6,11 @@ from szurubooru.rest import middleware logger = logging.getLogger(__name__) +@middleware.pre_hook +def process_request(_ctx): + db.reset_query_count() + + @middleware.post_hook def process_response(ctx): logger.info(