""" Author: Michel Peltriaux Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany Contact: michel.peltriaux@sgdnord.rlp.de Created on: 24.01.22 """ import json from abc import abstractmethod from django.contrib.gis import geos from django.contrib.gis.geos import GEOSGeometry class AbstractModelAPISerializer: model = None lookup = None properties_data = None class Meta: abstract = True def __init__(self, *args, **kwargs): self.lookup = { "id": None, # must be set "deleted__isnull": True, "users__in": [], # must be set } super().__init__(*args, **kwargs) @abstractmethod 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 Returns: """ raise NotImplementedError("Must be implemented in subclasses") @abstractmethod def prepare_lookup(self, _id, user): """ Updates lookup dict for db fetching Args: _id (str): The object's id user (User): The user requesting for Returns: """ self.lookup["id"] = _id self.lookup["users__in"] = [user] def fetch_and_serialize(self): """ Serializes the model entry according to the given lookup data Args: Returns: serialized_data (dict) """ entry = self.model.objects.get(**self.lookup) serialized_data = self.model_to_geo_json(entry) return serialized_data @abstractmethod def update_model_from_json(self, id, json_model, user): """ Updates an instance from given json data Args: id (str): The instance's to be updated json_model (dict): JSON data user (User): The performing user Returns: """ raise NotImplementedError("Must be implemented in subclasses") @abstractmethod def create_model_from_json(self, json_model, user): """ Creates a new instance from given json data Args: json_model (dict): JSON data user (User): The performing user Returns: """ raise NotImplementedError("Must be implemented in subclasses") def create_geometry_from_json(self, geojson) -> GEOSGeometry: """ Creates a GEOSGeometry object based on the given geojson Args: geojson (str|dict): The geojson as str or dict Returns: geometry (GEOSGeometry) """ if isinstance(geojson, dict): geojson = json.dumps(geojson) geometry = geos.fromstr(geojson) return geometry def get_obj_from_db(self, id, user): """ Returns the object from database Fails if id not found or user does not have shared access Args: id (str): The object's id user (User): The API user Returns: """ return self.model.objects.get( id=id, users__in=[user] )