author-followers-fix

This commit is contained in:
Untone 2025-05-30 13:48:02 +03:00
parent 6ba5c04564
commit f8ad73571c
4 changed files with 36 additions and 10 deletions

28
cache/cache.py vendored
View File

@ -108,17 +108,39 @@ async def update_follower_stat(follower_id, entity_type, count):
# Get author from cache # Get author from cache
async def get_cached_author(author_id: int, get_with_stat): 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}" author_key = f"author:id:{author_id}"
logger.debug(f"[get_cached_author] Проверка кэша по ключу: {author_key}")
result = await redis.execute("GET", author_key) result = await redis.execute("GET", author_key)
if result: 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 # Load from database if not found in cache
q = select(Author).where(Author.id == author_id) q = select(Author).where(Author.id == author_id)
authors = get_with_stat(q) authors = get_with_stat(q)
logger.debug(f"[get_cached_author] Результат запроса из БД: {len(authors) if authors else 0} записей")
if authors: if authors:
author = authors[0] author = authors[0]
await cache_author(author.dict()) logger.debug(f"[get_cached_author] Получен автор из БД: {type(author)}, id: {getattr(author, 'id', 'N/A')}")
return author.dict()
# Используем безопасный вызов 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 return None

View File

@ -108,6 +108,10 @@ async def get_current_user(_, info):
if authors_with_stat and len(authors_with_stat) > 0: 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 author.stat = authors_with_stat[0].stat
except Exception as e: except Exception as e:
logger.warning(f"[getSession] Не удалось добавить статистику к автору: {e}") logger.warning(f"[getSession] Не удалось добавить статистику к автору: {e}")

View File

@ -50,7 +50,7 @@ async def get_all_authors(current_user_id=None):
authors = session.execute(authors_query).scalars().unique().all() 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) return await cached_query(cache_key, fetch_all_authors)

View File

@ -69,7 +69,7 @@ async def follow(_, info, what, slug="", entity_id=0):
# Если это автор, учитываем фильтрацию данных # Если это автор, учитываем фильтрацию данных
if what == "AUTHOR": if what == "AUTHOR":
# Полная версия для кэширования # Полная версия для кэширования
entity_dict = entity.dict(is_admin=True) entity_dict = entity.dict(access=True)
else: else:
entity_dict = entity.dict() entity_dict = entity.dict()
@ -116,7 +116,7 @@ async def follow(_, info, what, slug="", entity_id=0):
if hasattr(temp_author, key): if hasattr(temp_author, key):
setattr(temp_author, key, value) 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: if not existing_sub:
# Создаем объект автора для entity_dict # Создаем объект автора для entity_dict
@ -125,7 +125,7 @@ async def follow(_, info, what, slug="", entity_id=0):
if hasattr(temp_author, key): if hasattr(temp_author, key):
setattr(temp_author, key, value) setattr(temp_author, key, value)
# Добавляем отфильтрованную версию # Добавляем отфильтрованную версию
follows = [*follows_filtered, temp_author.dict(viewer_id, False)] follows = [*follows_filtered, temp_author.dict(access=False)]
else: else:
follows = follows_filtered follows = follows_filtered
else: else:
@ -209,7 +209,7 @@ async def unfollow(_, info, what, slug="", entity_id=0):
logger.debug("Обновление кэша после отписки") logger.debug("Обновление кэша после отписки")
# Если это автор, кэшируем полную версию # Если это автор, кэшируем полную версию
if what == "AUTHOR": if what == "AUTHOR":
await cache_method(entity.dict(is_admin=True)) await cache_method(entity.dict(access=True))
else: else:
await cache_method(entity.dict()) await cache_method(entity.dict())
@ -232,7 +232,7 @@ async def unfollow(_, info, what, slug="", entity_id=0):
if hasattr(temp_author, key): if hasattr(temp_author, key):
setattr(temp_author, key, value) 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 follows = follows_filtered
else: else: