Add 6 lab code

This commit is contained in:
2026-11-25 12:55:15 +03:00
parent 20afc2c790
commit f6882a77b4
56 changed files with 3570 additions and 0 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')), prefix='history-v4')