Ticket #6773: find_serialization_errors.py

File find_serialization_errors.py, 4.2 KB (added by Ryan Witt, 14 years ago)

management command to find serialization errors

Line 
1from django.core.exceptions import ImproperlyConfigured
2from django.core.management.base import BaseCommand, CommandError
3from django.core import serializers
4from django.utils.datastructures import SortedDict
5
6from optparse import make_option
7
8class Command(BaseCommand):
9 option_list = BaseCommand.option_list + (
10 make_option('--format', default='json', dest='format',
11 help='Specifies the output serialization format for fixtures.'),
12 make_option('-e', '--exclude', dest='exclude',action='append', default=[],
13 help='App to exclude (use multiple --exclude to exclude multiple apps).'),
14 make_option('--stop-on-errors', action='store_true', dest='stop_on_errors',
15 help='Stop on encountering the first serialization error.'),
16 )
17 help = 'Identify all objects that are causing serialization errors.'
18 args = '[appname ...]'
19
20 def handle(self, *app_labels, **options):
21 import sys, traceback
22 from django.db.models import get_app, get_apps, get_models, get_model
23
24 format = options.get('format','json')
25 exclude = options.get('exclude',[])
26 show_traceback = options.get('traceback', False)
27 stop_on_errors = options.get('stop_on_errors', False)
28
29 excluded_apps = [get_app(app_label) for app_label in exclude]
30
31 if len(app_labels) == 0:
32 app_list = SortedDict([(app, None) for app in get_apps() if app not in excluded_apps])
33 else:
34 app_list = SortedDict()
35 for label in app_labels:
36 try:
37 app_label, model_label = label.split('.')
38 try:
39 app = get_app(app_label)
40 except ImproperlyConfigured:
41 raise CommandError("Unknown application: %s" % app_label)
42
43 model = get_model(app_label, model_label)
44 if model is None:
45 raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
46
47 if app in app_list.keys():
48 if app_list[app] and model not in app_list[app]:
49 app_list[app].append(model)
50 else:
51 app_list[app] = [model]
52 except ValueError:
53 # This is just an app - no model qualifier
54 app_label = label
55 try:
56 app = get_app(app_label)
57 except ImproperlyConfigured:
58 raise CommandError("Unknown application: %s" % app_label)
59 app_list[app] = None
60
61 # Check that the serialization format exists; this is a shortcut to
62 # avoid collating all the objects and _then_ failing.
63 if format not in serializers.get_public_serializer_formats():
64 raise CommandError("Unknown serialization format: %s" % format)
65
66 try:
67 serializers.get_serializer(format)
68 except KeyError:
69 raise CommandError("Unknown serialization format: %s" % format)
70
71 objects = []
72 for app, model_list in app_list.items():
73 if model_list is None:
74 model_list = get_models(app)
75
76 for model in model_list:
77 if not model._meta.proxy:
78 sys.stderr.write('Searching %s\n' % model)
79 try:
80 # Try serializing the whole lot first, before going one by one
81 serializers.serialize(format, model._default_manager.all())
82 except:
83 for instance in model._default_manager.all():
84 try:
85 serializers.serialize(format, model._default_manager.filter(pk=instance.pk))
86 except Exception, e:
87 sys.stderr.write('\nERROR IN %s instance: %s\n' % (model, `instance`))
88 sys.stdout.write('%s\n' % instance.__dict__)
89 if stop_on_errors:
90 raise
91 else:
92 sys.stderr.write(traceback.format_exc())
Back to Top