From 0f038ac6d71cc02a15a47bee647fe62557b24ab4 Mon Sep 17 00:00:00 2001 From: Untone Date: Thu, 22 Feb 2024 13:01:38 +0300 Subject: [PATCH] caching-author-fix --- resolvers/author.py | 22 +++------------------- services/follows.py | 21 +++------------------ 2 files changed, 6 insertions(+), 37 deletions(-) diff --git a/resolvers/author.py b/resolvers/author.py index 5270bb64..3b0223ae 100644 --- a/resolvers/author.py +++ b/resolvers/author.py @@ -133,12 +133,8 @@ async def load_author_with_stats(q): .count() ) author.stat['rating'] = likes_count - dislikes_count - author.stat['rating_shouts'] = count_author_shouts_rating( - session, author.id - ) - author.stat['rating_comments'] = count_author_comments_rating( - session, author.id - ) + author.stat['rating_shouts'] = count_author_shouts_rating(session, author.id) + author.stat['rating_comments'] = count_author_comments_rating(session, author.id) author.stat['commented'] = comments_count return author @@ -168,19 +164,7 @@ async def get_author_by_user_id(user_id: str): q = select(Author).filter(Author.user == user_id) author = await load_author_with_stats(q) if author: - await redis.execute( - 'set', - redis_key, - json.dumps( - { - 'id': author.id, - 'name': author.name, - 'slug': author.slug, - 'pic': author.pic, - 'bio': author.bio, - } - ), - ) + update_author(author) return author diff --git a/services/follows.py b/services/follows.py index e823b85c..8a942f99 100644 --- a/services/follows.py +++ b/services/follows.py @@ -9,24 +9,9 @@ from resolvers.stat import add_author_stat_columns, add_topic_stat_columns from services.rediscache import redis -async def update_author(author): +async def update_author(author: Author, ttl = 25 * 60 * 60): redis_key = f'user:{author.user}:author' - - await redis.execute( - 'SET', - redis_key, - json.dumps( - { - 'id': author.id, - 'name': author.name, - 'slug': author.slug, - 'pic': author.pic, - 'bio': author.bio, - 'stat': author.stat, - } - ), - ) - await redis.execute('EXPIRE', redis_key, 25 * 60 * 60) + await redis.execute('SETEX', redis_key, ttl, json.dumps(author.dict())) @event.listens_for(Author, 'after_insert') @@ -85,7 +70,7 @@ async def update_follows_for_user( follows[f'{entity_type}s'] = [ e for e in follows[f'{entity_type}s'] if e['id'] != entity['id'] ] - await redis.execute('set', redis_key, json.dumps(follows)) + await redis.execute('SET', redis_key, json.dumps(follows)) async def handle_author_follower_change(connection, author_id, follower_id, is_insert):