author-followers-fix
This commit is contained in:
parent
6ba5c04564
commit
f8ad73571c
28
cache/cache.py
vendored
28
cache/cache.py
vendored
|
@ -108,17 +108,39 @@ async def update_follower_stat(follower_id, entity_type, count):
|
|||
|
||||
# Get author from cache
|
||||
async def get_cached_author(author_id: int, get_with_stat):
|
||||
logger.debug(f"[get_cached_author] Начало выполнения для author_id: {author_id}")
|
||||
|
||||
author_key = f"author:id:{author_id}"
|
||||
logger.debug(f"[get_cached_author] Проверка кэша по ключу: {author_key}")
|
||||
|
||||
result = await redis.execute("GET", author_key)
|
||||
if result:
|
||||
return orjson.loads(result)
|
||||
logger.debug(f"[get_cached_author] Найдены данные в кэше, размер: {len(result)} байт")
|
||||
cached_data = orjson.loads(result)
|
||||
logger.debug(f"[get_cached_author] Кэшированные данные имеют ключи: {list(cached_data.keys()) if cached_data else 'None'}")
|
||||
return cached_data
|
||||
|
||||
logger.debug(f"[get_cached_author] Данные не найдены в кэше, загрузка из БД")
|
||||
|
||||
# Load from database if not found in cache
|
||||
q = select(Author).where(Author.id == author_id)
|
||||
authors = get_with_stat(q)
|
||||
logger.debug(f"[get_cached_author] Результат запроса из БД: {len(authors) if authors else 0} записей")
|
||||
|
||||
if authors:
|
||||
author = authors[0]
|
||||
await cache_author(author.dict())
|
||||
return author.dict()
|
||||
logger.debug(f"[get_cached_author] Получен автор из БД: {type(author)}, id: {getattr(author, 'id', 'N/A')}")
|
||||
|
||||
# Используем безопасный вызов dict() для Author
|
||||
author_dict = author.dict() if hasattr(author, 'dict') else author.__dict__
|
||||
logger.debug(f"[get_cached_author] Сериализованные данные автора: {list(author_dict.keys()) if author_dict else 'None'}")
|
||||
|
||||
await cache_author(author_dict)
|
||||
logger.debug(f"[get_cached_author] Автор кэширован")
|
||||
|
||||
return author_dict
|
||||
|
||||
logger.warning(f"[get_cached_author] Автор с ID {author_id} не найден в БД")
|
||||
return None
|
||||
|
||||
|
||||
|
|
|
@ -108,6 +108,10 @@ async def get_current_user(_, info):
|
|||
|
||||
if authors_with_stat and len(authors_with_stat) > 0:
|
||||
# Обновляем только статистику
|
||||
# Проверяем, является ли author объектом или словарем
|
||||
if isinstance(author, dict):
|
||||
author["stat"] = authors_with_stat[0].stat
|
||||
else:
|
||||
author.stat = authors_with_stat[0].stat
|
||||
except Exception as e:
|
||||
logger.warning(f"[getSession] Не удалось добавить статистику к автору: {e}")
|
||||
|
|
|
@ -50,7 +50,7 @@ async def get_all_authors(current_user_id=None):
|
|||
authors = session.execute(authors_query).scalars().unique().all()
|
||||
|
||||
# Преобразуем авторов в словари с учетом прав доступа
|
||||
return [author.dict(current_user_id, False) for author in authors]
|
||||
return [author.dict(access=False) for author in authors]
|
||||
|
||||
# Используем универсальную функцию для кеширования запросов
|
||||
return await cached_query(cache_key, fetch_all_authors)
|
||||
|
|
|
@ -69,7 +69,7 @@ async def follow(_, info, what, slug="", entity_id=0):
|
|||
# Если это автор, учитываем фильтрацию данных
|
||||
if what == "AUTHOR":
|
||||
# Полная версия для кэширования
|
||||
entity_dict = entity.dict(is_admin=True)
|
||||
entity_dict = entity.dict(access=True)
|
||||
else:
|
||||
entity_dict = entity.dict()
|
||||
|
||||
|
@ -116,7 +116,7 @@ async def follow(_, info, what, slug="", entity_id=0):
|
|||
if hasattr(temp_author, key):
|
||||
setattr(temp_author, key, value)
|
||||
# Добавляем отфильтрованную версию
|
||||
follows_filtered.append(temp_author.dict(viewer_id, False))
|
||||
follows_filtered.append(temp_author.dict(access=False))
|
||||
|
||||
if not existing_sub:
|
||||
# Создаем объект автора для entity_dict
|
||||
|
@ -125,7 +125,7 @@ async def follow(_, info, what, slug="", entity_id=0):
|
|||
if hasattr(temp_author, key):
|
||||
setattr(temp_author, key, value)
|
||||
# Добавляем отфильтрованную версию
|
||||
follows = [*follows_filtered, temp_author.dict(viewer_id, False)]
|
||||
follows = [*follows_filtered, temp_author.dict(access=False)]
|
||||
else:
|
||||
follows = follows_filtered
|
||||
else:
|
||||
|
@ -209,7 +209,7 @@ async def unfollow(_, info, what, slug="", entity_id=0):
|
|||
logger.debug("Обновление кэша после отписки")
|
||||
# Если это автор, кэшируем полную версию
|
||||
if what == "AUTHOR":
|
||||
await cache_method(entity.dict(is_admin=True))
|
||||
await cache_method(entity.dict(access=True))
|
||||
else:
|
||||
await cache_method(entity.dict())
|
||||
|
||||
|
@ -232,7 +232,7 @@ async def unfollow(_, info, what, slug="", entity_id=0):
|
|||
if hasattr(temp_author, key):
|
||||
setattr(temp_author, key, value)
|
||||
# Добавляем отфильтрованную версию
|
||||
follows_filtered.append(temp_author.dict(viewer_id, False))
|
||||
follows_filtered.append(temp_author.dict(access=False))
|
||||
|
||||
follows = follows_filtered
|
||||
else:
|
||||
|
|
Loading…
Reference in New Issue
Block a user