FEAT: Modernized to support latest Pythons and DRF JSONAPI
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""Shared extensions for Django REST framework JSON:API."""
|
||||
|
||||
__version__ = "1.1.0"
|
||||
|
||||
+68
-62
@@ -1,88 +1,94 @@
|
||||
"""Reusable serializers and views for DRF JSON:API applications."""
|
||||
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.generics import GenericAPIView
|
||||
from rest_framework_json_api import serializers
|
||||
from rest_framework_json_api.utils import get_included_resources
|
||||
from rest_framework_json_api.views import AutoPrefetchMixin, RelatedMixin
|
||||
|
||||
basic_filter = ('exact', 'isnull')
|
||||
text_filter = ('exact', 'contains', 'iexact', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith')
|
||||
date_filter = ('exact', 'gte', 'lte')
|
||||
int_filter = ('exact', 'gte', 'lte')
|
||||
from .exceptions import HardenedExceptionHandlingMixin
|
||||
|
||||
basic_filter = ("exact", "isnull")
|
||||
text_filter = (
|
||||
"exact",
|
||||
"contains",
|
||||
"iexact",
|
||||
"icontains",
|
||||
"startswith",
|
||||
"istartswith",
|
||||
"endswith",
|
||||
"iendswith",
|
||||
)
|
||||
date_filter = ("exact", "gte", "lte")
|
||||
int_filter = ("exact", "gte", "lte")
|
||||
|
||||
|
||||
class PreloadIncludesMixin(object):
|
||||
"""
|
||||
This mixin provides a helper attributes to select or prefetch related models
|
||||
based on the include specified in the URL.
|
||||
|
||||
__all__ can be used to specify a prefetch which should be done regardless of the include
|
||||
|
||||
|
||||
.. code:: python
|
||||
|
||||
# When MyViewSet is called with ?include=author it will prefetch author and authorbio
|
||||
class MyViewSet(viewsets.ModelViewSet):
|
||||
queryset = Book.objects.all()
|
||||
prefetch_for_includes = {
|
||||
'__all__': [],
|
||||
'category.section': ['category']
|
||||
}
|
||||
select_for_includes = {
|
||||
'__all__': [],
|
||||
'author': ['author', 'author__authorbio'],
|
||||
}
|
||||
"""
|
||||
class PreloadIncludesMixin:
|
||||
"""Apply configured select/prefetch rules for requested JSON:API includes."""
|
||||
|
||||
def get_select_related(self, include):
|
||||
return getattr(self, 'select_for_includes', {}).get(include, None)
|
||||
return getattr(self, "select_for_includes", {}).get(include)
|
||||
|
||||
def get_prefetch_related(self, include):
|
||||
return getattr(self, 'prefetch_for_includes', {}).get(include, None)
|
||||
return getattr(self, "prefetch_for_includes", {}).get(include)
|
||||
|
||||
def get_queryset(self, *args, **kwargs):
|
||||
qs = super(PreloadIncludesMixin, self).get_queryset(*args, **kwargs)
|
||||
queryset = super().get_queryset(*args, **kwargs)
|
||||
includes = [*get_included_resources(self.request), "__all__"]
|
||||
|
||||
included_resources = get_included_resources(self.request)
|
||||
for included in included_resources + ['__all__']:
|
||||
|
||||
select_related = self.get_select_related(included)
|
||||
for include in includes:
|
||||
select_related = self.get_select_related(include)
|
||||
if select_related is not None:
|
||||
qs = qs.select_related(*select_related)
|
||||
queryset = queryset.select_related(*select_related)
|
||||
|
||||
prefetch_related = self.get_prefetch_related(included)
|
||||
if prefetch_related is not None:
|
||||
if not isinstance(prefetch_related, list):
|
||||
qs = qs.prefetch_related(*prefetch_related(self))
|
||||
else:
|
||||
qs = qs.prefetch_related(*prefetch_related)
|
||||
prefetch_related = self.get_prefetch_related(include)
|
||||
if prefetch_related is None:
|
||||
continue
|
||||
if callable(prefetch_related):
|
||||
prefetch_related = prefetch_related(self)
|
||||
queryset = queryset.prefetch_related(*prefetch_related)
|
||||
|
||||
return qs
|
||||
return queryset
|
||||
|
||||
|
||||
class ReasonableModelViewSet(AutoPrefetchMixin,
|
||||
PreloadIncludesMixin,
|
||||
RelatedMixin,
|
||||
viewsets.ModelViewSet):
|
||||
http_method_names = ['get', 'post', 'patch', 'delete', 'head', 'options']
|
||||
class ReasonableModelViewSet(
|
||||
AutoPrefetchMixin,
|
||||
PreloadIncludesMixin,
|
||||
RelatedMixin,
|
||||
viewsets.ModelViewSet,
|
||||
):
|
||||
"""JSON:API model viewset limited to the standard resource methods."""
|
||||
|
||||
http_method_names = ["get", "post", "patch", "delete", "head", "options"]
|
||||
|
||||
|
||||
class HardenedModelViewSet(HardenedExceptionHandlingMixin, ReasonableModelViewSet):
|
||||
"""ReasonableModelViewSet with sanitized handling for unexpected errors."""
|
||||
|
||||
|
||||
class HardenedGenericAPIView(HardenedExceptionHandlingMixin, GenericAPIView):
|
||||
"""GenericAPIView with sanitized handling for unexpected errors."""
|
||||
|
||||
|
||||
class ReasonableModelSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Reusable class to extend DJA ModelSerializer and make it more JSONAPI compatible
|
||||
"""
|
||||
"""Include declared relationship fields requested by JSON:API clients."""
|
||||
|
||||
def get_field_names(self, declared_fields, info):
|
||||
method = self.context['request'].method
|
||||
fields = list(super().get_field_names(declared_fields, info))
|
||||
request = self.context.get("request")
|
||||
included_serializers = getattr(self, "included_serializers", {})
|
||||
if request is None or not included_serializers:
|
||||
return fields
|
||||
|
||||
included_rel_fields = []
|
||||
if method == 'GET':
|
||||
included_rel_fields = [qp for qp in (
|
||||
self.context['request'].query_params['include'].split(',')
|
||||
if 'include' in self.context['request'].query_params else []
|
||||
) if qp in (self.included_serializers if hasattr(self, 'included_serializers') else [])]
|
||||
elif method == 'POST' or method == 'PATCH':
|
||||
included_rel_fields = [irel for irel in (
|
||||
self.context['request'].data.keys()
|
||||
) if irel in (self.included_serializers if hasattr(self, 'included_serializers') else [])]
|
||||
included_relationships = []
|
||||
if request.method == "GET":
|
||||
included_relationships = request.query_params.get("include", "").split(",")
|
||||
elif request.method in {"POST", "PATCH"}:
|
||||
included_relationships = request.data.keys()
|
||||
|
||||
fields = super().get_field_names(declared_fields, info)
|
||||
return fields + included_rel_fields
|
||||
fields.extend(
|
||||
relationship
|
||||
for relationship in included_relationships
|
||||
if relationship in included_serializers and relationship not in fields
|
||||
)
|
||||
return fields
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Safe, JSON:API-compatible exception handling."""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from rest_framework.exceptions import APIException
|
||||
from rest_framework_json_api.exceptions import exception_handler as jsonapi_exception_handler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ERROR_ID_HEADER = "X-Error-ID"
|
||||
|
||||
|
||||
class APIConflictException(APIException):
|
||||
"""A deliberately raised, non-sensitive resource conflict."""
|
||||
|
||||
status_code = 409
|
||||
default_detail = "The request conflicts with the current resource state."
|
||||
default_code = "conflict"
|
||||
|
||||
|
||||
class InternalServerError(APIException):
|
||||
"""Sanitized representation of an unexpected server exception."""
|
||||
|
||||
status_code = 500
|
||||
default_detail = "An unexpected server error occurred."
|
||||
default_code = "internal_error"
|
||||
|
||||
|
||||
def hardened_exception_handler(exc, context):
|
||||
"""Render expected errors normally and sanitize unexpected exceptions.
|
||||
|
||||
Unexpected exception details and tracebacks are logged server-side under a
|
||||
generated error identifier. Only that opaque identifier is returned to the
|
||||
client, in a response header, so operators can correlate a report safely.
|
||||
"""
|
||||
|
||||
response = jsonapi_exception_handler(exc, context)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
error_id = uuid.uuid4().hex
|
||||
logger.error(
|
||||
"Unhandled API exception; error_id=%s",
|
||||
error_id,
|
||||
exc_info=exc,
|
||||
)
|
||||
|
||||
response = jsonapi_exception_handler(InternalServerError(), context)
|
||||
response[ERROR_ID_HEADER] = error_id
|
||||
return response
|
||||
|
||||
|
||||
class HardenedExceptionHandlingMixin:
|
||||
"""Opt a DRF view into :func:`hardened_exception_handler`."""
|
||||
|
||||
def get_exception_handler(self):
|
||||
return hardened_exception_handler
|
||||
@@ -1,37 +1,35 @@
|
||||
from collections import OrderedDict
|
||||
"""Pagination adapters for clients built with ngx-jsonapi."""
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework_json_api.pagination import JsonApiPageNumberPagination
|
||||
|
||||
|
||||
class NgxJsonApiPageNumberPagination(JsonApiPageNumberPagination):
|
||||
"""Expose page-number metadata in the shape expected by ngx-jsonapi."""
|
||||
|
||||
def get_paginated_response(self, data):
|
||||
next = None
|
||||
previous = None
|
||||
next_page = None
|
||||
previous_page = None
|
||||
|
||||
if self.page.has_next():
|
||||
next = self.page.next_page_number()
|
||||
next_page = self.page.next_page_number()
|
||||
if self.page.has_previous():
|
||||
previous = self.page.previous_page_number()
|
||||
previous_page = self.page.previous_page_number()
|
||||
|
||||
return Response(
|
||||
{
|
||||
"results": data,
|
||||
"meta": OrderedDict(
|
||||
[
|
||||
("page", self.page.number),
|
||||
("pages", self.page.paginator.num_pages),
|
||||
("total_resources", self.page.paginator.count),
|
||||
("resources_per_page", self.page.paginator.per_page),
|
||||
]
|
||||
),
|
||||
"links": OrderedDict(
|
||||
[
|
||||
("first", self.build_link(1)),
|
||||
("last", self.build_link(self.page.paginator.num_pages)),
|
||||
("next", self.build_link(next)),
|
||||
("prev", self.build_link(previous)),
|
||||
]
|
||||
),
|
||||
"meta": {
|
||||
"page": self.page.number,
|
||||
"pages": self.page.paginator.num_pages,
|
||||
"total_resources": self.page.paginator.count,
|
||||
"resources_per_page": self.page.paginator.per_page,
|
||||
},
|
||||
"links": {
|
||||
"first": self.build_link(1),
|
||||
"last": self.build_link(self.page.paginator.num_pages),
|
||||
"next": self.build_link(next_page),
|
||||
"prev": self.build_link(previous_page),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user