This commit is contained in:
parent
ff9c0a0b82
commit
13acff1708
35
cache/cache.py
vendored
35
cache/cache.py
vendored
|
@ -139,27 +139,40 @@ async def get_cached_authors_by_ids(author_ids: List[int]) -> List[dict]:
|
||||||
return authors
|
return authors
|
||||||
|
|
||||||
|
|
||||||
# Get cached topic followers
|
|
||||||
async def get_cached_topic_followers(topic_id: int):
|
async def get_cached_topic_followers(topic_id: int):
|
||||||
# Attempt to retrieve cached data
|
"""
|
||||||
cached = await redis.execute("get", f"topic:followers:{topic_id}")
|
Получает подписчиков темы по ID, используя кеш Redis.
|
||||||
|
Если данные отсутствуют в кеше, извлекает из базы данных и кеширует их.
|
||||||
|
|
||||||
|
:param topic_id: Идентификатор темы, подписчиков которой необходимо получить.
|
||||||
|
:return: Список подписчиков темы, каждый элемент представляет собой словарь с ID и именем автора.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Попытка получить данные из кеша
|
||||||
|
cached = await redis.get(f"topic:followers:{topic_id}")
|
||||||
if cached:
|
if cached:
|
||||||
followers = json.loads(cached)
|
followers = json.loads(cached)
|
||||||
logger.debug(f"Cached followers for topic#{topic_id}: {len(followers)}")
|
logger.debug(f"Cached followers for topic#{topic_id}: {len(followers)}")
|
||||||
return followers
|
return followers
|
||||||
|
|
||||||
# Load from database and cache results
|
# Если данные не найдены в кеше, загрузка из базы данных
|
||||||
with local_session() as session:
|
async with local_session() as session:
|
||||||
followers_ids = [
|
result = await session.execute(
|
||||||
f[0]
|
session.query(Author.id)
|
||||||
for f in session.query(Author.id)
|
|
||||||
.join(TopicFollower, TopicFollower.follower == Author.id)
|
.join(TopicFollower, TopicFollower.follower == Author.id)
|
||||||
.filter(TopicFollower.topic == topic_id)
|
.filter(TopicFollower.topic == topic_id)
|
||||||
.all()
|
)
|
||||||
]
|
followers_ids = [f[0] for f in result.scalars().all()]
|
||||||
await redis.execute("SET", f"topic:followers:{topic_id}", json.dumps(followers_ids))
|
|
||||||
|
# Кеширование результатов
|
||||||
|
await redis.set(f"topic:followers:{topic_id}", json.dumps(followers_ids))
|
||||||
|
|
||||||
|
# Получение подробной информации о подписчиках по их ID
|
||||||
followers = await get_cached_authors_by_ids(followers_ids)
|
followers = await get_cached_authors_by_ids(followers_ids)
|
||||||
return followers
|
return followers
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка при получении подписчиков для темы#{topic_id}: {str(e)}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
# Get cached author followers
|
# Get cached author followers
|
||||||
|
|
Loading…
Reference in New Issue
Block a user