summaryrefslogtreecommitdiff
path: root/ishtar_common/serializers.py
diff options
context:
space:
mode:
Diffstat (limited to 'ishtar_common/serializers.py')
-rw-r--r--ishtar_common/serializers.py58
1 files changed, 58 insertions, 0 deletions
diff --git a/ishtar_common/serializers.py b/ishtar_common/serializers.py
index d7d998e96..31caa8cb7 100644
--- a/ishtar_common/serializers.py
+++ b/ishtar_common/serializers.py
@@ -1,6 +1,64 @@
+import datetime
+import os
+import tempfile
from rest_framework import serializers
+from zipfile import ZipFile
+
+from django.apps import apps
+from django.core.serializers import serialize
+
+from . import models
class PublicSerializer(serializers.BaseSerializer):
def to_representation(self, obj):
return obj.public_representation()
+
+
+def type_model_serialization(archive=False, return_empty_types=False,
+ archive_name=None):
+ """
+ Serialize all types models to JSON
+ Used for import and export scripts
+
+ :param return_empty_types: if True instead of serialization return empty
+ types (default False)
+ :param archive: if True return a zip file containing all the file serialized
+ (defaukt False)
+ :return: string containing the json serialization of types unless
+ return_empty_types or archive is set to True
+ """
+ if archive and return_empty_types:
+ raise ValueError("archive and return_empty_types are incompatible")
+ result = {}
+ for model in apps.get_models():
+ if not isinstance(model(), models.GeneralType):
+ continue
+ model_name = model.__name__
+ model_name = str(model.__module__).split(".")[0] + "__" + model_name
+ result[model_name] = serialize(
+ "json", model.objects.all(),
+ indent=2,
+ use_natural_foreign_keys=True, use_natural_primary_keys=True
+ )
+ if return_empty_types:
+ return [k for k in result if not result[k]]
+ if not archive:
+ return result
+ if not archive_name:
+ tmpdir = tempfile.mkdtemp(prefix="ishtarexport-") + os.sep
+ archive_name = tmpdir + "ishtar-{}.zip".format(
+ datetime.date.today().strftime("%Y-%m-%d")
+ )
+ if not archive_name.endswith(".zip"):
+ archive_name += ".zip"
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ with ZipFile(archive_name, 'w') as current_zip:
+ for model_name in result:
+ base_filename = model_name + ".json"
+ filename = tmpdirname + os.sep + base_filename
+ with open(filename, "w") as json_file:
+ json_file.write(result[model_name])
+ current_zip.write(filename, arcname=base_filename)
+ return archive_name
+