From b12db9af0ee7fdd7d09ab589ecba3111e843bbd4 Mon Sep 17 00:00:00 2001 From: Untone Date: Sun, 25 Feb 2024 19:02:15 +0300 Subject: [PATCH] faster-get-author --- resolvers/author.py | 24 +++++++++++++++--------- services/event_listeners.py | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/resolvers/author.py b/resolvers/author.py index 5f7a514b..fcba7c00 100644 --- a/resolvers/author.py +++ b/resolvers/author.py @@ -40,16 +40,22 @@ def get_authors_all(_, _info): async def get_author(_, _info, slug='', author_id=None): q = None author = None + cache = None try: - if slug or author_id: - if bool(slug): - q = select(Author).where(Author.slug == slug) - if author_id: - q = select(Author).where(Author.id == author_id) - - [author] = get_with_stat(q) - if author: - await update_author_cache(author) + if slug: + with local_session() as session: + q = select(Author).filter(Author.slug == slug) + [author] = session.execute(q) + author_id = author.id + if author_id: + cache = await redis.execute('GET', f'id:{author_id}:author') + if not cache: + q = select(Author).where(Author.id == author_id) + [author] = get_with_stat(q) + if author: + await update_author_cache(author) + else: + author = json.loads(cache) except Exception as exc: logger.error(exc) return author diff --git a/services/event_listeners.py b/services/event_listeners.py index 0e57f7b3..5318076b 100644 --- a/services/event_listeners.py +++ b/services/event_listeners.py @@ -21,7 +21,7 @@ DEFAULT_FOLLOWS = { async def update_author_cache(author: Author, ttl=25 * 60 * 60): payload = json.dumps(author.dict()) await redis.execute('SETEX', f'user:{author.user}:author', ttl, payload) - await redis.execute('SETEX', f'id:{author.user}:author', ttl, payload) + await redis.execute('SETEX', f'id:{author.id}:author', ttl, payload) @event.listens_for(Shout, 'after_insert')