authors-stats-fix2
Some checks failed
Deploy on push / deploy (push) Failing after 3m33s

This commit is contained in:
2025-08-31 22:54:40 +03:00
parent e63517a887
commit 7258ddf059
2 changed files with 34 additions and 41 deletions

View File

@@ -764,34 +764,23 @@ async def get_author(
if "stat" in cached_author: if "stat" in cached_author:
author_dict["stat"] = cached_author["stat"] author_dict["stat"] = cached_author["stat"]
# ВСЕГДА используем новый резолвер для получения полной статистики if not author_dict or not author_dict.get("stat"):
try: # Используем ту же логику что и в load_authors_by
# Используем новый резолвер для получения полной статистики try:
filter_by: AuthorsBy = {} filter_by: AuthorsBy = {}
if slug: if slug:
filter_by["slug"] = slug filter_by["slug"] = slug
elif author_id: elif author_id:
filter_by["id"] = author_id # author_id уже int filter_by["id"] = author_id
logger.debug(f"Calling get_authors_with_stats with filter: {filter_by}") authors_with_stats = await get_authors_with_stats(limit=1, offset=0, by=filter_by)
authors_with_stats = await get_authors_with_stats(limit=1, offset=0, by=filter_by) if authors_with_stats and len(authors_with_stats) > 0:
author_dict = authors_with_stats[0]
if authors_with_stats and len(authors_with_stats) > 0: # Кэшируем полные данные
author_dict = authors_with_stats[0] _t = asyncio.create_task(cache_author(author_dict))
logger.debug(f"Got author with stats: shouts={author_dict.get('stat', {}).get('shouts', 'missing')}") except Exception as e:
logger.error(f"Error getting author stats: {e}")
# Фильтруем данные согласно правам доступа # Fallback к старому методу
if not is_admin:
# Убираем защищенные поля для не-админов
protected_fields = ["email", "phone"]
for field in protected_fields:
author_dict.pop(field, None)
# Кэшируем полные данные для админов
_t = asyncio.create_task(cache_author(author_dict))
else:
logger.warning(f"No author found with filter: {filter_by}")
# Fallback to basic author data without stats
with local_session() as session: with local_session() as session:
if slug: if slug:
author = session.query(Author).filter_by(slug=slug).first() author = session.query(Author).filter_by(slug=slug).first()
@@ -799,17 +788,6 @@ async def get_author(
author = session.query(Author).filter_by(id=author_id).first() author = session.query(Author).filter_by(id=author_id).first()
if author: if author:
author_dict = author.dict(is_admin) author_dict = author.dict(is_admin)
logger.debug(f"Using fallback author dict: {author_dict.get('name', 'unknown')}")
except Exception as e:
logger.error(f"Error getting author stats: {e}")
# Fallback to basic author data without stats
with local_session() as session:
if slug:
author = session.query(Author).filter_by(slug=slug).first()
else:
author = session.query(Author).filter_by(id=author_id).first()
if author:
author_dict = author.dict(is_admin)
except ValueError: except ValueError:
pass pass
except Exception as exc: except Exception as exc:

View File

@@ -413,8 +413,14 @@ async def create_reaction(_: None, info: GraphQLResolveInfo, reaction: dict) ->
shout = session.query(Shout).where(Shout.id == shout_id).first() shout = session.query(Shout).where(Shout.id == shout_id).first()
if not shout: if not shout:
return {"error": "Shout not found"} return {"error": "Shout not found"}
# Получаем полного автора из БД вместо неполного из контекста
author = session.query(Author).where(Author.id == author_id).first()
if not author:
return {"error": "Author not found"}
rdict["shout"] = shout.dict() rdict["shout"] = shout.dict()
rdict["created_by"] = author_dict rdict["created_by"] = author.dict()
return {"reaction": rdict} return {"reaction": rdict}
except Exception as e: except Exception as e:
traceback.print_exc() traceback.print_exc()
@@ -470,7 +476,10 @@ async def update_reaction(_: None, info: GraphQLResolveInfo, reaction: dict) ->
await notify_reaction(r, "update") await notify_reaction(r, "update")
return {"reaction": r.dict()} # Включаем полную информацию об авторе в ответ
reaction_dict = r.dict()
reaction_dict["created_by"] = author.dict()
return {"reaction": reaction_dict}
return {"error": "Reaction not found"} return {"error": "Reaction not found"}
except Exception as e: except Exception as e:
logger.error(f"{type(e).__name__}: {e}") logger.error(f"{type(e).__name__}: {e}")
@@ -527,7 +536,13 @@ async def delete_reaction(_: None, info: GraphQLResolveInfo, reaction_id: int) -
await notify_reaction(r, "delete") await notify_reaction(r, "delete")
return {"error": None, "reaction": r.dict()} # Включаем полную информацию об авторе в ответ
reaction_dict = r.dict()
reaction_author: Author | None = session.query(Author).where(Author.id == r.created_by).first()
if reaction_author:
reaction_dict["created_by"] = reaction_author.dict()
return {"error": None, "reaction": reaction_dict}
except Exception as e: except Exception as e:
logger.error(f"{type(e).__name__}: {e}") logger.error(f"{type(e).__name__}: {e}")
return {"error": "Cannot delete reaction"} return {"error": "Cannot delete reaction"}