konova/api/views/views.py
mpeltriaux a03f9c8c78 #31 API POST Intervention
* adds support for proper POST of intervention
* makes /<id> optional (required for Post)
2022-01-24 12:17:17 +01:00

68 lines
1.9 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 django.http import JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
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
"""
serializer = None
user = 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)
self.serializer = self.serializer()
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
try:
# Fetch the proper user from the given request header token
self.user = APIUserToken.get_user_from_token(request.headers.get(KSP_TOKEN_HEADER_IDENTIFIER, None))
except PermissionError as e:
return self.return_error_response(e, 403)
return super().dispatch(request, *args, **kwargs)
def return_error_response(self, error, status_code=500):
""" Returns an error as JsonReponse
Args:
error (): The error/exception
status_code (): The desired status code
Returns:
"""
content = [error.__str__()]
if hasattr(error, "messages"):
content = error.messages
return JsonResponse(
{
"errors": content
},
status=status_code
)