maloja/maloja/database/jinjaview.py

52 lines
1.4 KiB
Python
Raw Normal View History

from .. import database
2022-02-26 23:30:06 +03:00
from . sqldb import engine
2022-02-27 04:51:44 +03:00
from .dbcache import serialize
from ..pkg_global.conf import malojaconfig
2022-02-27 04:51:44 +03:00
2022-03-12 10:28:48 +03:00
from doreah.logging import log
# this is a wrapper object that provides a DB connection so that one jinja page
# (with all its included partials) can use it for all functions
# it also translates the non-unpacked calls to unpacked calls that the DB wants
2022-02-27 04:51:44 +03:00
# it also maintains a request-local cache since many webpages use the same stats
# several times
class JinjaDBConnection:
2022-02-27 04:51:44 +03:00
def __init__(self):
self.cache = {}
2022-03-12 10:28:48 +03:00
self.hits = 0
self.misses = 0
2022-02-26 23:30:06 +03:00
def __enter__(self):
self.conn = engine.connect()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.conn.close()
2022-04-25 04:24:16 +03:00
if malojaconfig['USE_REQUEST_CACHE']:
log(f"Generated page with {self.hits}/{self.hits+self.misses} local Cache hits",module="debug_performance")
2022-03-12 10:28:48 +03:00
del self.cache
def __getattr__(self,name):
originalmethod = getattr(database,name)
def packedmethod(*keys):
kwargs = {}
for k in keys:
kwargs.update(k)
2022-02-27 04:51:44 +03:00
if malojaconfig['USE_REQUEST_CACHE']:
cachekey = serialize((id(originalmethod),kwargs))
if cachekey in self.cache:
2022-03-12 10:28:48 +03:00
self.hits += 1
2022-02-27 04:51:44 +03:00
return self.cache[cachekey]
else:
2022-03-12 10:28:48 +03:00
self.misses += 1
2022-02-27 04:51:44 +03:00
result = originalmethod(**kwargs,dbconn=self.conn)
self.cache[cachekey] = result
return result
else:
result = originalmethod(**kwargs,dbconn=self.conn)
return result
return packedmethod