From 280a55046ae2154860b5e6f81e98c6df6a5b70e3 Mon Sep 17 00:00:00 2001 From: rr- Date: Wed, 24 Aug 2016 12:28:51 +0200 Subject: [PATCH] server/db: make query counter thread-local --- server/szurubooru/db/session.py | 36 +++++++++---------- server/szurubooru/middleware/db_session.py | 1 - .../szurubooru/middleware/request_logger.py | 5 +++ 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/server/szurubooru/db/session.py b/server/szurubooru/db/session.py index 98ad150..3fb1fb9 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 8f8a1a5..4a2fe96 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 c430ca4..47b43ab 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(