Add second lab code

This commit is contained in:
2026-10-23 15:12:43 +03:00
parent 0ab3a341aa
commit cd9c3402fa
40 changed files with 1692 additions and 10 deletions
+40
View File
@@ -0,0 +1,40 @@
"""History pages are disposable; PostgreSQL owns both data and their version."""
import hashlib
import json
import os
from redis.exceptions import RedisError
from .auth import sessions
class HistoryCache:
def __init__(self, client, ttl=30, prefix='history'):
self.client = client
self.ttl = ttl
self.prefix = prefix
if ttl < 1:
raise ValueError('CACHE_TTL_SECONDS must be positive')
def key(self, chat_id, version, limit, after):
page = json.dumps([limit, after], separators=(',', ':'))
digest = hashlib.sha256(page.encode()).hexdigest()
return f'{self.prefix}:{chat_id}:{version}:{digest}'
def get_or_load(self, chat_id, version, limit, after, load):
key = self.key(chat_id, version, limit, after)
try:
cached = self.client.get(key)
except RedisError:
return load()
if cached is not None:
return json.loads(cached)
page = load()
try:
self.client.set(key, json.dumps(page, ensure_ascii=False), ex=self.ttl)
except RedisError:
pass
return page
history_cache = HistoryCache(sessions.client, int(os.getenv('CACHE_TTL_SECONDS', '30')))