add aurweb.cache, a redis caching utility module

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-08-06 22:44:19 -07:00
parent 968ed736c1
commit 9e73936c4e
No known key found for this signature in database
GPG key ID: F7E46DED420788F3
2 changed files with 94 additions and 0 deletions

20
aurweb/cache.py Normal file
View file

@ -0,0 +1,20 @@
from redis import Redis
from sqlalchemy import orm
async def db_count_cache(redis: Redis, key: str, query: orm.Query,
expire: int = None) -> int:
""" Store and retrieve a query.count() via redis cache.
:param redis: Redis handle
:param key: Redis key
:param query: SQLAlchemy ORM query
:param expire: Optional expiration in seconds
:return: query.count()
"""
result = redis.get(key)
if result is None:
redis.set(key, (result := int(query.count())))
if expire:
redis.expire(key, expire)
return int(result)