diff --git a/.gitignore b/.gitignore index dd1996b..8f967e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .vscode .idea +.ruff_cache __pycache__ diff --git a/fastapi_book_server/app/services/common.py b/fastapi_book_server/app/services/common.py index c0c52c6..f6c27d3 100644 --- a/fastapi_book_server/app/services/common.py +++ b/fastapi_book_server/app/services/common.py @@ -315,7 +315,7 @@ class GetRandomService(Generic[MODEL, QUERY], BaseService[MODEL, QUERY]): cls, query: QUERY, redis: aioredis.Redis, - ) -> int: + ) -> int | None: cached_object_id = await cls._get_random_object_from_cache(query, redis) if cached_object_id is not None: @@ -325,6 +325,9 @@ class GetRandomService(Generic[MODEL, QUERY], BaseService[MODEL, QUERY]): await cls.cache_object_ids(query, object_ids, redis) + if len(object_ids): + return None + return choice(object_ids) diff --git a/fastapi_book_server/app/views/author.py b/fastapi_book_server/app/views/author.py index 8020882..46dfd67 100644 --- a/fastapi_book_server/app/views/author.py +++ b/fastapi_book_server/app/views/author.py @@ -43,6 +43,9 @@ async def get_random_author( {"allowed_langs": allowed_langs}, request.app.state.redis ) + if author_id is None: + raise HTTPException(status.HTTP_204_NO_CONTENT) + return ( await AuthorDB.objects.select_related(SELECT_RELATED_FIELDS) .prefetch_related(PREFETCH_RELATED_FIELDS) diff --git a/fastapi_book_server/app/views/book.py b/fastapi_book_server/app/views/book.py index e10ffee..b162220 100644 --- a/fastapi_book_server/app/views/book.py +++ b/fastapi_book_server/app/views/book.py @@ -64,6 +64,9 @@ async def get_random_book( {"allowed_langs": allowed_langs, "genre": genre}, request.app.state.redis ) + if book_id is None: + raise HTTPException(status.HTTP_204_NO_CONTENT) + book = ( await BookDB.objects.select_related( SELECT_RELATED_FIELDS + DETAIL_SELECT_RELATED_FIELDS diff --git a/fastapi_book_server/app/views/sequence.py b/fastapi_book_server/app/views/sequence.py index b5553f9..b099ddf 100644 --- a/fastapi_book_server/app/views/sequence.py +++ b/fastapi_book_server/app/views/sequence.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, Depends, Request +from fastapi import APIRouter, Depends, HTTPException, Request, status from fastapi_pagination import Params from fastapi_pagination.ext.ormar import paginate @@ -34,6 +34,9 @@ async def get_random_sequence( request.app.state.redis, ) + if sequence_id is None: + raise HTTPException(status.HTTP_204_NO_CONTENT) + return await SequenceDB.objects.get(id=sequence_id)