diff options
author | Étienne Loks <etienne.loks@iggdrasil.net> | 2019-08-29 15:12:00 +0200 |
---|---|---|
committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2019-09-01 10:32:52 +0200 |
commit | 73f30398883b1f7659beb07751ec2677378200d3 (patch) | |
tree | 35e8ebc417fd322f6e42b4d476b1086f9ead3f08 /ishtar_common/serializers.py | |
parent | cad70d1e9abee60747c9e9591efb8ac16943d777 (diff) | |
download | Ishtar-73f30398883b1f7659beb07751ec2677378200d3.tar.bz2 Ishtar-73f30398883b1f7659beb07751ec2677378200d3.zip |
Serialization: serialize types for import/export
Diffstat (limited to 'ishtar_common/serializers.py')
-rw-r--r-- | ishtar_common/serializers.py | 58 |
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 + |