You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
konova/api/views/views.py

69 lines
1.8 KiB
Python

"""
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
class Meta:
abstract = True
@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, _filter):
""" Serializes the model entry according to the given lookup data
Args:
_filter (dict): Lookup declarations
Returns:
serialized_data (dict)
"""
qs = self.model.objects.filter(**_filter)
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)