Перенести собственную реализацию лабораторной 2 с сохранением контракта лабораторной 3
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
|
||||
import logging
|
||||
import os
|
||||
from redis import Redis, RedisError
|
||||
from pydantic import ValidationError
|
||||
from src.config import setting
|
||||
from src.models import User
|
||||
|
||||
|
||||
class ProfileCache:
|
||||
def __init__(self):
|
||||
url = setting('CACHE_URL')
|
||||
self.client = Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2, max_connections=16) if url else None
|
||||
self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60'))
|
||||
self.hits = self.misses = self.errors = 0
|
||||
|
||||
def get(self, user_id):
|
||||
if not self.client:
|
||||
return None
|
||||
try:
|
||||
value = self.client.get('profile:v1:'+user_id)
|
||||
if value:
|
||||
user=User.model_validate_json(value)
|
||||
if user.id != user_id:
|
||||
raise ValueError('неверный ключ кэша')
|
||||
self.hits += 1
|
||||
return user
|
||||
self.misses += 1
|
||||
except (RedisError, ValidationError, ValueError):
|
||||
self.errors += 1
|
||||
logging.getLogger(__name__).warning('Кэш профиля недоступен; чтение из PostgreSQL')
|
||||
return None
|
||||
|
||||
def put(self, user):
|
||||
if self.client:
|
||||
try:
|
||||
self.client.set('profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
|
||||
except RedisError:
|
||||
self.errors += 1
|
||||
|
||||
|
||||
profile_cache = ProfileCache()
|
||||
Reference in New Issue
Block a user