From 5ad1b35dc0c9426020f0d014c82627023c373393 Mon Sep 17 00:00:00 2001 From: mpeltriaux Date: Mon, 24 Jan 2022 13:12:29 +0100 Subject: [PATCH] #31 API basic implementation Cleanup * cleans code * reworks many code fragments into smaller methods and split into super class --- api/utils/serializer/serializer.py | 19 ++++++++++++++- api/utils/serializer/v1/intervention.py | 32 +++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/api/utils/serializer/serializer.py b/api/utils/serializer/serializer.py index bbe49279..5febafc8 100644 --- a/api/utils/serializer/serializer.py +++ b/api/utils/serializer/serializer.py @@ -117,4 +117,21 @@ class AbstractModelAPISerializer: if isinstance(geojson, dict): geojson = json.dumps(geojson) geometry = geos.fromstr(geojson) - return geometry \ No newline at end of file + 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] + ) \ No newline at end of file diff --git a/api/utils/serializer/v1/intervention.py b/api/utils/serializer/v1/intervention.py index 65be4ea6..7e5028e3 100644 --- a/api/utils/serializer/v1/intervention.py +++ b/api/utils/serializer/v1/intervention.py @@ -135,3 +135,35 @@ class InterventionAPISerializerV1(AbstractModelAPISerializerV1): celery_update_parcels.delay(obj.geometry.id) return obj.id + + def update_model_from_json(self, id, json_model, user): + """ Updates an entry for the model based on the contents of json_model + + Args: + id (str): The object's id + json_model (dict): The json containing data + user (User): The API user + + Returns: + created_id (str): The id of the newly created Intervention entry + """ + with transaction.atomic(): + obj = self.get_obj_from_db(id, user) + + # Fill in data to objects + properties = json_model["properties"] + obj.title = properties["title"] + self.set_responsibility(obj, properties["responsible"]) + self.set_legal(obj, properties["legal"]) + obj.geometry.geom = self.create_geometry_from_json(json_model) + + obj.responsible.save() + obj.geometry.save() + obj.legal.save() + obj.save() + + obj.users.add(user) + + celery_update_parcels.delay(obj.geometry.id) + + return obj.id