This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
portail-citoyen/portail_citoyen/management/commands/exportpage.py

80 lines
2.9 KiB
Python

import json
from optparse import make_option
from django.core.management.base import BaseCommand
from django.core.serializers.json import DjangoJSONEncoder
from cms.models import Page, CMSPlugin
from django.core import serializers
from pprint import pprint
exclude_attrs = {'Page': ('parent', 'site', 'placeholders',
'reverse_id', 'publisher_public'),
'Placeholder': (),
'CMSPlugin': ('placeholder', 'parent',),
'Title': ('page', )
}
class Command(BaseCommand):
help = 'Dumps CMS page and its content(if required)'
args = 'output.json'
option_list = BaseCommand.option_list + (
make_option('--page', action='store', default=1),
make_option('--output', action='store', default='dump.json')
)
def _serialize(self, data):
obj_type = data._meta.object_name
raw_data = serializers.serialize('python', [data])[0]
raw_data.pop('pk')
# remove useless key
map(lambda attr: raw_data['fields'].pop(attr), exclude_attrs[obj_type])
# return '%s(%s)' % (data.id, type(data))
return json.dumps(raw_data, cls=DjangoJSONEncoder)
def _get_object_descendants(self, obj, obj_dict={}, **options):
"""
returns the hierarchy
"""
obj_dump = self._serialize(obj)
obj_dict[obj_dump] = []
if isinstance(obj, Page):
# its a CMS Page
placeholders = obj.placeholders.all()
if placeholders:
for placeholder in placeholders:
placeholder_dump = self._serialize(placeholder)
plugins = placeholder.cmsplugin_set.filter(parent__isnull=True)
if plugins:
hierarchy = []
for plugin in plugins:
hierarchy.append(self._get_object_descendants(plugin, {}))
obj_dict[obj_dump].append({placeholder_dump: hierarchy})
else:
obj_dict[obj_dump].append(placeholder_dump)
# add related titles
titles = obj.title_set.all()
if titles:
for title in titles:
obj_dict[obj_dump].append(self._serialize(title))
children = obj.get_children()
if children:
for child in children:
descendants = self._get_object_descendants(child, {})
child_dump = self._serialize(child)
if descendants:
obj_dict[obj_dump].append(descendants)
else:
obj_dict[obj_dump].append(child)
return obj_dict
def handle(self, *args, **options):
page = Page.objects.get(pk=options['page'])
with open(options.get('output'), 'w') as output:
json.dump(self._get_object_descendants(page), output)