blob: 31caa8cb785ee430061ba62f65c80007b8b1d158 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
|