""" Author: Michel Peltriaux Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany Contact: michel.peltriaux@sgdnord.rlp.de Created on: 21.01.22 """ from abc import abstractmethod from django.http import JsonResponse from django.views import View from api.models import APIUserToken from api.settings import KSP_TOKEN_HEADER_IDENTIFIER class AbstractModelAPIView(View): """ Base class for API views The API must follow the GeoJSON Specification RFC 7946 https://geojson.org/ https://datatracker.ietf.org/doc/html/rfc7946 """ model = None user = None lookup = None class Meta: abstract = True def __init__(self, *args, **kwargs): self.lookup = { "id": None, # must be set in subclasses "deleted__isnull": True, "users__in": [], # must be set in subclasses } super().__init__(*args, **kwargs) @abstractmethod def model_to_json(self, entry): """ Defines the returned json values of the model Args: entry (): The found entry from the database Returns: """ raise NotImplementedError("Must be implemented in subclasses") def fetch_and_serialize(self): """ Serializes the model entry according to the given lookup data Args: Returns: serialized_data (dict) """ qs = self.model.objects.filter(**self.lookup) serialized_data = {} for entry in qs: serialized_data[str(entry.pk)] = self.model_to_json(entry) return serialized_data def dispatch(self, request, *args, **kwargs): try: self.user = APIUserToken.get_user_from_token(request.headers.get(KSP_TOKEN_HEADER_IDENTIFIER, None)) except PermissionError as e: return JsonResponse( { "error": e.__str__() }, status=403 ) return super().dispatch(request, *args, **kwargs)