Ticket #5423: 5423.2.diff

File 5423.2.diff, 5.9 KB (added by ramiro, 5 years ago)

Another update, with fixes to JSON output so it is always syntactically correct.

  • django/core/management/commands/dumpdata.py

    diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py
    a b  
    11from django.core.exceptions import ImproperlyConfigured
    22from django.core.management.base import BaseCommand, CommandError
    33from django.core import serializers
    4 from django.db import connections, router, DEFAULT_DB_ALIAS
     4from django.db import router, DEFAULT_DB_ALIAS
    55from django.utils.datastructures import SortedDict
    66
    77from optparse import make_option
     
    2828    args = '[appname appname.ModelName ...]'
    2929
    3030    def handle(self, *app_labels, **options):
    31         from django.db.models import get_app, get_apps, get_models, get_model
     31        from django.db.models import get_app, get_apps, get_model
    3232
    33         format = options.get('format','json')
    34         indent = options.get('indent',None)
     33        format = options.get('format', 'json')
     34        indent = options.get('indent', None)
    3535        using = options.get('database', DEFAULT_DB_ALIAS)
    36         connection = connections[using]
    37         excludes = options.get('exclude',[])
     36        excludes = options.get('exclude', [])
    3837        show_traceback = options.get('traceback', False)
    3938        use_natural_keys = options.get('use_natural_keys', False)
    4039        use_base_manager = options.get('use_base_manager', False)
     
    9897        except KeyError:
    9998            raise CommandError("Unknown serialization format: %s" % format)
    10099
    101         # Now collate the objects to be serialized.
    102         objects = []
    103         for model in sort_dependencies(app_list.items()):
    104             if model in excluded_models:
    105                 continue
    106             if not model._meta.proxy and router.allow_syncdb(using, model):
    107                 if use_base_manager:
    108                     objects.extend(model._base_manager.using(using).all())
    109                 else:
    110                     objects.extend(model._default_manager.using(using).all())
     100        def get_objects ():
     101            # Collate the objects to be serialized.
     102            for model in sort_dependencies(app_list.items()):
     103                if model in excluded_models:
     104                    continue
     105                if not model._meta.proxy and router.allow_syncdb(using, model):
     106                    if use_base_manager:
     107                        for obj in model._base_manager.using(using).order_by(model._meta.pk.name).iterator():
     108                            yield obj
     109                    else:
     110                        for obj in model._default_manager.using(using).order_by(model._meta.pk.name).iterator():
     111                            yield obj
    111112
    112113        try:
    113             return serializers.serialize(format, objects, indent=indent,
    114                         use_natural_keys=use_natural_keys)
     114            return serializers.serialize(format, get_objects(), indent=indent,
     115                    use_natural_keys=use_natural_keys)
    115116        except Exception, e:
    116117            if show_traceback:
    117118                raise
  • django/core/serializers/base.py

    diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py
    a b  
    3636        self.use_natural_keys = options.pop("use_natural_keys", False)
    3737
    3838        self.start_serialization()
     39        self.first = True
    3940        for obj in queryset:
    4041            self.start_object(obj)
    4142            for field in obj._meta.local_fields:
     
    5152                    if self.selected_fields is None or field.attname in self.selected_fields:
    5253                        self.handle_m2m_field(obj, field)
    5354            self.end_object(obj)
     55            if self.first:
     56                self.first = False
    5457        self.end_serialization()
    5558        return self.getvalue()
    5659
  • django/core/serializers/json.py

    diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
    a b  
    1717    """
    1818    internal_use_only = False
    1919
     20    def start_serialization(self):
     21        self._current = None
     22        self.json_kwargs = self.options.copy()
     23        self.json_kwargs.pop('stream', None)
     24        self.json_kwargs.pop('fields', None)
     25        self.stream.write("[")
     26
    2027    def end_serialization(self):
    21         simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options)
     28        if self.options.get("indent"):
     29            self.stream.write("\n")
     30        self.stream.write("]")
     31        if self.options.get("indent"):
     32            self.stream.write("\n")
     33
     34    def end_object(self, obj):
     35        # self._current has the field data
     36        indent = self.options.get("indent")
     37        if not self.first:
     38            self.stream.write(",")
     39            if not indent:
     40                self.stream.write(" ")
     41        if indent:
     42            self.stream.write("\n")
     43        simplejson.dump(self.get_dump_object(obj), self.stream,
     44                        cls=DjangoJSONEncoder, **self.json_kwargs)
     45        self._current = None
    2246
    2347    def getvalue(self):
     48        # overwrite PythonSerializer.getvalue() with base Serializer.getvalue()
    2449        if callable(getattr(self.stream, 'getvalue', None)):
    2550            return self.stream.getvalue()
    2651
  • django/core/serializers/python.py

    diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py
    a b  
    2727        self._current = {}
    2828
    2929    def end_object(self, obj):
    30         self.objects.append({
     30        self.objects.append(self.get_dump_object(obj))
     31        self._current = None
     32
     33    def get_dump_object (self, obj):
     34        return {
    3135            "model"  : smart_unicode(obj._meta),
    3236            "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
    3337            "fields" : self._current
    34         })
    35         self._current = None
     38        }
    3639
    3740    def handle_field(self, obj, field):
    3841        value = field._get_val_from_obj(obj)
Back to Top