2006-06-29 00:00:37 +08:00
|
|
|
"""
|
|
|
|
Interfaces for serializing Django objects.
|
|
|
|
|
|
|
|
Usage::
|
|
|
|
|
2007-09-15 16:29:56 +08:00
|
|
|
from django.core import serializers
|
2013-03-08 22:15:23 +08:00
|
|
|
json = serializers.serialize("json", some_queryset)
|
2007-09-15 16:29:56 +08:00
|
|
|
objects = list(serializers.deserialize("json", json))
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
To add your own serializers, use the SERIALIZATION_MODULES setting::
|
|
|
|
|
|
|
|
SERIALIZATION_MODULES = {
|
2013-10-27 09:27:42 +08:00
|
|
|
"csv": "path.to.csv.serializer",
|
|
|
|
"txt": "path.to.txt.serializer",
|
2006-06-29 00:00:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2013-07-29 21:50:58 +08:00
|
|
|
import importlib
|
|
|
|
|
2014-10-15 23:37:23 +08:00
|
|
|
from django.apps import apps
|
2006-06-29 00:00:37 +08:00
|
|
|
from django.conf import settings
|
2011-04-27 00:49:32 +08:00
|
|
|
from django.core.serializers.base import SerializerDoesNotExist
|
2006-06-29 00:00:37 +08:00
|
|
|
|
|
|
|
# Built-in serializers
|
|
|
|
BUILTIN_SERIALIZERS = {
|
2013-10-27 09:27:42 +08:00
|
|
|
"xml": "django.core.serializers.xml_serializer",
|
|
|
|
"python": "django.core.serializers.python",
|
|
|
|
"json": "django.core.serializers.json",
|
|
|
|
"yaml": "django.core.serializers.pyyaml",
|
2006-06-29 00:00:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
_serializers = {}
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2013-09-06 23:56:06 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BadSerializer:
|
2013-09-06 23:56:06 +08:00
|
|
|
"""
|
|
|
|
Stub serializer to hold exception raised during registration
|
|
|
|
|
|
|
|
This allows the serializer registration to cache serializers and if there
|
|
|
|
is an error raised in the process of creating a serializer it will be
|
|
|
|
raised and passed along to the caller when the serializer is used.
|
|
|
|
"""
|
|
|
|
internal_use_only = False
|
|
|
|
|
|
|
|
def __init__(self, exception):
|
|
|
|
self.exception = exception
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
raise self.exception
|
|
|
|
|
|
|
|
|
2008-08-15 19:53:49 +08:00
|
|
|
def register_serializer(format, serializer_module, serializers=None):
|
2010-12-04 12:27:05 +08:00
|
|
|
"""Register a new serializer.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-15 19:53:49 +08:00
|
|
|
``serializer_module`` should be the fully qualified module name
|
|
|
|
for the serializer.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-15 19:53:49 +08:00
|
|
|
If ``serializers`` is provided, the registration will be added
|
|
|
|
to the provided dictionary.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-15 19:53:49 +08:00
|
|
|
If ``serializers`` is not provided, the registration will be made
|
|
|
|
directly into the global register of serializers. Adding serializers
|
|
|
|
directly is not a thread-safe operation.
|
|
|
|
"""
|
2011-01-27 10:29:17 +08:00
|
|
|
if serializers is None and not _serializers:
|
|
|
|
_load_serializers()
|
2013-09-06 23:56:06 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
module = importlib.import_module(serializer_module)
|
2013-09-07 08:07:57 +08:00
|
|
|
except ImportError as exc:
|
2013-09-06 23:56:06 +08:00
|
|
|
bad_serializer = BadSerializer(exc)
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
module = type('BadSerializerModule', (), {
|
2013-09-06 23:56:06 +08:00
|
|
|
'Deserializer': bad_serializer,
|
|
|
|
'Serializer': bad_serializer,
|
|
|
|
})
|
|
|
|
|
2008-08-15 19:53:49 +08:00
|
|
|
if serializers is None:
|
|
|
|
_serializers[format] = module
|
|
|
|
else:
|
|
|
|
serializers[format] = module
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-09-06 23:56:06 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
def unregister_serializer(format):
|
2008-08-15 19:53:49 +08:00
|
|
|
"Unregister a given serializer. This is not a thread-safe operation."
|
2011-01-27 10:29:17 +08:00
|
|
|
if not _serializers:
|
|
|
|
_load_serializers()
|
2011-04-27 00:49:32 +08:00
|
|
|
if format not in _serializers:
|
|
|
|
raise SerializerDoesNotExist(format)
|
2006-06-29 00:00:37 +08:00
|
|
|
del _serializers[format]
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
def get_serializer(format):
|
|
|
|
if not _serializers:
|
|
|
|
_load_serializers()
|
2011-04-27 00:49:32 +08:00
|
|
|
if format not in _serializers:
|
|
|
|
raise SerializerDoesNotExist(format)
|
2006-06-29 00:00:37 +08:00
|
|
|
return _serializers[format].Serializer
|
2007-03-01 21:11:08 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-03-01 21:11:08 +08:00
|
|
|
def get_serializer_formats():
|
|
|
|
if not _serializers:
|
|
|
|
_load_serializers()
|
2012-08-08 22:33:15 +08:00
|
|
|
return list(_serializers)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-12-17 14:53:15 +08:00
|
|
|
def get_public_serializer_formats():
|
|
|
|
if not _serializers:
|
|
|
|
_load_serializers()
|
2017-01-07 19:11:46 +08:00
|
|
|
return [k for k, v in _serializers.items() if not v.Serializer.internal_use_only]
|
2007-12-17 14:53:15 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
def get_deserializer(format):
|
|
|
|
if not _serializers:
|
|
|
|
_load_serializers()
|
2011-04-27 00:49:32 +08:00
|
|
|
if format not in _serializers:
|
|
|
|
raise SerializerDoesNotExist(format)
|
2006-06-29 00:00:37 +08:00
|
|
|
return _serializers[format].Deserializer
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
def serialize(format, queryset, **options):
|
|
|
|
"""
|
|
|
|
Serialize a queryset (or any iterator that returns database objects) using
|
|
|
|
a certain serializer.
|
|
|
|
"""
|
|
|
|
s = get_serializer(format)()
|
|
|
|
s.serialize(queryset, **options)
|
|
|
|
return s.getvalue()
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def deserialize(format, stream_or_string, **options):
|
2006-06-29 00:00:37 +08:00
|
|
|
"""
|
2017-01-26 03:02:33 +08:00
|
|
|
Deserialize a stream or a string. Return an iterator that yields ``(obj,
|
2014-05-29 08:39:14 +08:00
|
|
|
m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* --
|
2006-06-29 00:00:37 +08:00
|
|
|
object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
|
|
|
|
list_of_related_objects}``.
|
|
|
|
"""
|
|
|
|
d = get_deserializer(format)
|
2009-12-22 23:18:51 +08:00
|
|
|
return d(stream_or_string, **options)
|
2006-06-29 00:00:37 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-06-29 00:00:37 +08:00
|
|
|
def _load_serializers():
|
|
|
|
"""
|
|
|
|
Register built-in and settings-defined serializers. This is done lazily so
|
|
|
|
that user code has a chance to (e.g.) set up custom settings without
|
|
|
|
needing to be careful of import order.
|
|
|
|
"""
|
2008-08-15 19:53:49 +08:00
|
|
|
global _serializers
|
|
|
|
serializers = {}
|
2006-06-29 00:00:37 +08:00
|
|
|
for format in BUILTIN_SERIALIZERS:
|
2008-08-15 19:53:49 +08:00
|
|
|
register_serializer(format, BUILTIN_SERIALIZERS[format], serializers)
|
2006-06-29 00:00:37 +08:00
|
|
|
if hasattr(settings, "SERIALIZATION_MODULES"):
|
|
|
|
for format in settings.SERIALIZATION_MODULES:
|
2008-08-15 19:53:49 +08:00
|
|
|
register_serializer(format, settings.SERIALIZATION_MODULES[format], serializers)
|
|
|
|
_serializers = serializers
|
2014-10-15 23:37:23 +08:00
|
|
|
|
|
|
|
|
|
|
|
def sort_dependencies(app_list):
|
|
|
|
"""Sort a list of (app_config, models) pairs into a single list of models.
|
|
|
|
|
|
|
|
The single list of models is sorted so that any model with a natural key
|
|
|
|
is serialized before a normal model, and any model with a natural key
|
|
|
|
dependency has it's dependencies serialized first.
|
|
|
|
"""
|
|
|
|
# Process the list of models, and get the list of dependencies
|
|
|
|
model_dependencies = []
|
|
|
|
models = set()
|
|
|
|
for app_config, model_list in app_list:
|
|
|
|
if model_list is None:
|
|
|
|
model_list = app_config.get_models()
|
|
|
|
|
|
|
|
for model in model_list:
|
|
|
|
models.add(model)
|
|
|
|
# Add any explicitly defined dependencies
|
|
|
|
if hasattr(model, 'natural_key'):
|
|
|
|
deps = getattr(model.natural_key, 'dependencies', [])
|
|
|
|
if deps:
|
|
|
|
deps = [apps.get_model(dep) for dep in deps]
|
|
|
|
else:
|
|
|
|
deps = []
|
|
|
|
|
|
|
|
# Now add a dependency for any FK relation with a model that
|
|
|
|
# defines a natural key
|
|
|
|
for field in model._meta.fields:
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field:
|
|
|
|
rel_model = field.remote_field.model
|
2014-10-15 23:37:23 +08:00
|
|
|
if hasattr(rel_model, 'natural_key') and rel_model != model:
|
|
|
|
deps.append(rel_model)
|
|
|
|
# Also add a dependency for any simple M2M relation with a model
|
|
|
|
# that defines a natural key. M2M relations with explicit through
|
|
|
|
# models don't count as dependencies.
|
|
|
|
for field in model._meta.many_to_many:
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field.through._meta.auto_created:
|
|
|
|
rel_model = field.remote_field.model
|
2014-10-15 23:37:23 +08:00
|
|
|
if hasattr(rel_model, 'natural_key') and rel_model != model:
|
|
|
|
deps.append(rel_model)
|
|
|
|
model_dependencies.append((model, deps))
|
|
|
|
|
|
|
|
model_dependencies.reverse()
|
|
|
|
# Now sort the models to ensure that dependencies are met. This
|
|
|
|
# is done by repeatedly iterating over the input list of models.
|
|
|
|
# If all the dependencies of a given model are in the final list,
|
|
|
|
# that model is promoted to the end of the final list. This process
|
|
|
|
# continues until the input list is empty, or we do a full iteration
|
|
|
|
# over the input models without promoting a model to the final list.
|
|
|
|
# If we do a full iteration without a promotion, that means there are
|
|
|
|
# circular dependencies in the list.
|
|
|
|
model_list = []
|
|
|
|
while model_dependencies:
|
|
|
|
skipped = []
|
|
|
|
changed = False
|
|
|
|
while model_dependencies:
|
|
|
|
model, deps = model_dependencies.pop()
|
|
|
|
|
|
|
|
# If all of the models in the dependency list are either already
|
|
|
|
# on the final model list, or not on the original serialization list,
|
|
|
|
# then we've found another model with all it's dependencies satisfied.
|
2018-01-04 07:37:23 +08:00
|
|
|
if all(d not in models or d in model_list for d in deps):
|
2014-10-15 23:37:23 +08:00
|
|
|
model_list.append(model)
|
|
|
|
changed = True
|
|
|
|
else:
|
|
|
|
skipped.append((model, deps))
|
|
|
|
if not changed:
|
2016-03-29 06:33:29 +08:00
|
|
|
raise RuntimeError(
|
|
|
|
"Can't resolve dependencies for %s in serialized app list." %
|
|
|
|
', '.join(
|
|
|
|
'%s.%s' % (model._meta.app_label, model._meta.object_name)
|
|
|
|
for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__)
|
|
|
|
)
|
2014-10-15 23:37:23 +08:00
|
|
|
)
|
|
|
|
model_dependencies = skipped
|
|
|
|
|
|
|
|
return model_list
|