create-shout-fix2

This commit is contained in:
Untone 2025-01-21 18:28:03 +03:00
parent 1ed185a701
commit 8432a00691
2 changed files with 16 additions and 16 deletions

View File

@ -110,16 +110,16 @@ async def create_shout(_, info, inp):
author_id = int(author_id) author_id = int(author_id)
current_time = int(time.time()) current_time = int(time.time())
slug = inp.get("slug") or f"draft-{current_time}" slug = inp.get("slug") or f"draft-{current_time}"
logger.info(f"Creating shout with slug: {slug}") logger.info(f"Creating shout with slug: {slug}")
# Создаем объект Shout напрямую, без промежуточного словаря # Правильно:
new_shout = Shout({ new_shout = Shout(
**inp, **inp, # распаковываем входные данные
"slug": slug, slug=slug, # явно указываем именованные аргументы
"created_by": author_id, created_by=author_id,
"created_at": current_time created_at=current_time,
}) )
# Check for duplicate slug # Check for duplicate slug
logger.debug(f"Checking for existing slug: {slug}") logger.debug(f"Checking for existing slug: {slug}")
@ -195,7 +195,7 @@ async def create_shout(_, info, inp):
try: try:
author = session.query(Author).filter(Author.id == author_id).first() author = session.query(Author).filter(Author.id == author_id).first()
if author and author.stat: if author and author.stat:
author.stat["shouts"] = (author.stat.get("shouts", 0) + 1) author.stat["shouts"] = author.stat.get("shouts", 0) + 1
session.add(author) session.add(author)
session.commit() session.commit()
await cache_author(author.dict()) await cache_author(author.dict())
@ -336,7 +336,7 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
# Инвалидация кэша после обновления # Инвалидация кэша после обновления
try: try:
logger.info("Invalidating cache after shout update") logger.info("Invalidating cache after shout update")
cache_keys = [ cache_keys = [
"feed", # лента "feed", # лента
f"author_{author_id}", # публикации автора f"author_{author_id}", # публикации автора
@ -348,7 +348,7 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
for topic in shout_by_id.topics: for topic in shout_by_id.topics:
cache_keys.append(f"topic_{topic.id}") cache_keys.append(f"topic_{topic.id}")
cache_keys.append(f"topic_shouts_{topic.id}") cache_keys.append(f"topic_shouts_{topic.id}")
# Добавляем ключи для новых тем (если есть в shout_input) # Добавляем ключи для новых тем (если есть в shout_input)
if shout_input.get("topics"): if shout_input.get("topics"):
for topic in shout_input["topics"]: for topic in shout_input["topics"]:
@ -357,13 +357,13 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
cache_keys.append(f"topic_shouts_{topic.id}") cache_keys.append(f"topic_shouts_{topic.id}")
await invalidate_shouts_cache(cache_keys) await invalidate_shouts_cache(cache_keys)
# Обновляем кэш тем и авторов # Обновляем кэш тем и авторов
for topic in shout_by_id.topics: for topic in shout_by_id.topics:
await cache_by_id(Topic, topic.id, cache_topic) await cache_by_id(Topic, topic.id, cache_topic)
for author in shout_by_id.authors: for author in shout_by_id.authors:
await cache_author(author.dict()) await cache_author(author.dict())
logger.info("Cache invalidated successfully") logger.info("Cache invalidated successfully")
except Exception as cache_error: except Exception as cache_error:
logger.warning(f"Cache invalidation error: {cache_error}", exc_info=True) logger.warning(f"Cache invalidation error: {cache_error}", exc_info=True)

View File

@ -343,7 +343,7 @@ def apply_sorting(q, options):
async def load_shouts_by(_, info: GraphQLResolveInfo, options): async def load_shouts_by(_, info: GraphQLResolveInfo, options):
""" """
Загрузка публикаций с фильтрацией, сортировкой и пагинацией. Загрузка публикаций с фильтрацией, сортировкой и пагинацией.
:param _: Корневой объект запроса (не используется) :param _: Корневой объект запроса (не используется)
:param info: Информация о контексте GraphQL :param info: Информация о контексте GraphQL
:param options: Опции фильтрации и сортировки :param options: Опции фильтрации и сортировки
@ -351,7 +351,7 @@ async def load_shouts_by(_, info: GraphQLResolveInfo, options):
""" """
# Базовый запрос со статистикой # Базовый запрос со статистикой
q = query_with_stat(info) q = query_with_stat(info)
# Применяем остальные опции фильтрации # Применяем остальные опции фильтрации
q, limit, offset = apply_options(q, options) q, limit, offset = apply_options(q, options)