1
0
mirror of https://github.com/etesync/server synced 2024-11-22 16:58:08 +00:00

Utils: add a utility for getting objects or 404ing.

This commit is contained in:
Tom Hacohen 2020-12-27 18:34:23 +02:00
parent e7721e8fe5
commit e686f01652
2 changed files with 15 additions and 4 deletions

View File

@ -16,6 +16,7 @@ from .authentication import get_authenticated_user
from .exceptions import ValidationError, transform_validation_error
from .msgpack import MsgpackRoute, MsgpackResponse
from .stoken_handler import filter_by_stoken_and_limit, filter_by_stoken, get_stoken_obj, get_queryset_stoken
from .utils import get_object_or_404
User = get_user_model()
collection_router = APIRouter(route_class=MsgpackRoute)
@ -205,10 +206,7 @@ def get_collection_queryset(user: User, queryset: QuerySet) -> QuerySet:
def get_item_queryset(
user: User, collection_uid: str, queryset: QuerySet = default_item_queryset
) -> t.Tuple[models.Collection, QuerySet]:
try:
collection = get_collection_queryset(user, models.Collection.objects).get(uid=collection_uid)
except models.Collection.DoesNotExist:
raise ValidationError("does_not_exist", "Collection does not exist", status_code=status.HTTP_404_NOT_FOUND)
collection = get_object_or_404(get_collection_queryset(user, models.Collection.objects), uid=collection_uid)
# XXX Potentially add this for performance: .prefetch_related('revisions__chunks')
queryset = queryset.filter(collection__pk=collection.pk, revisions__current=True)

13
etebase_fastapi/utils.py Normal file
View File

@ -0,0 +1,13 @@
from fastapi import status
from django.db.models import QuerySet
from django.core.exceptions import ObjectDoesNotExist
from .exceptions import ValidationError
def get_object_or_404(queryset: QuerySet, **kwargs):
try:
return queryset.get(**kwargs)
except ObjectDoesNotExist as e:
raise ValidationError("does_not_exist", str(e), status_code=status.HTTP_404_NOT_FOUND)