#31 API basic implementation Cleanup
* cleans code * reworks many code fragments into smaller methods and split into super class
This commit is contained in:
@@ -25,6 +25,7 @@ class AbstractModelAPIView(View):
|
||||
model = None
|
||||
user = None
|
||||
lookup = None
|
||||
properties_data = None
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
@@ -38,8 +39,20 @@ class AbstractModelAPIView(View):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@abstractmethod
|
||||
def model_to_json(self, entry):
|
||||
""" Defines the returned json values of the model
|
||||
def model_to_geo_json(self, entry):
|
||||
""" Defines the model as geo json
|
||||
|
||||
Args:
|
||||
entry (): The found entry from the database
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
raise NotImplementedError("Must be implemented in subclasses")
|
||||
|
||||
@abstractmethod
|
||||
def extend_properties_data(self, entry):
|
||||
""" Defines the 'properties' part of geo json
|
||||
|
||||
Args:
|
||||
entry (): The found entry from the database
|
||||
@@ -57,20 +70,33 @@ class AbstractModelAPIView(View):
|
||||
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)
|
||||
entry = self.model.objects.get(**self.lookup)
|
||||
serialized_data = self.model_to_geo_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 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
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user