You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serializer.py 12KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import builtins
  2. import collections.abc
  3. import datetime
  4. import decimal
  5. import enum
  6. import functools
  7. import math
  8. import re
  9. import types
  10. import uuid
  11. from collections import OrderedDict
  12. from django.conf import SettingsReference
  13. from django.db import models
  14. from django.db.migrations.operations.base import Operation
  15. from django.db.migrations.utils import COMPILED_REGEX_TYPE, RegexObject
  16. from django.utils.functional import LazyObject, Promise
  17. from django.utils.timezone import utc
  18. from django.utils.version import get_docs_version
  19. class BaseSerializer:
  20. def __init__(self, value):
  21. self.value = value
  22. def serialize(self):
  23. raise NotImplementedError('Subclasses of BaseSerializer must implement the serialize() method.')
  24. class BaseSequenceSerializer(BaseSerializer):
  25. def _format(self):
  26. raise NotImplementedError('Subclasses of BaseSequenceSerializer must implement the _format() method.')
  27. def serialize(self):
  28. imports = set()
  29. strings = []
  30. for item in self.value:
  31. item_string, item_imports = serializer_factory(item).serialize()
  32. imports.update(item_imports)
  33. strings.append(item_string)
  34. value = self._format()
  35. return value % (", ".join(strings)), imports
  36. class BaseSimpleSerializer(BaseSerializer):
  37. def serialize(self):
  38. return repr(self.value), set()
  39. class DateTimeSerializer(BaseSerializer):
  40. """For datetime.*, except datetime.datetime."""
  41. def serialize(self):
  42. return repr(self.value), {'import datetime'}
  43. class DatetimeDatetimeSerializer(BaseSerializer):
  44. """For datetime.datetime."""
  45. def serialize(self):
  46. if self.value.tzinfo is not None and self.value.tzinfo != utc:
  47. self.value = self.value.astimezone(utc)
  48. imports = ["import datetime"]
  49. if self.value.tzinfo is not None:
  50. imports.append("from django.utils.timezone import utc")
  51. return repr(self.value).replace('<UTC>', 'utc'), set(imports)
  52. class DecimalSerializer(BaseSerializer):
  53. def serialize(self):
  54. return repr(self.value), {"from decimal import Decimal"}
  55. class DeconstructableSerializer(BaseSerializer):
  56. @staticmethod
  57. def serialize_deconstructed(path, args, kwargs):
  58. name, imports = DeconstructableSerializer._serialize_path(path)
  59. strings = []
  60. for arg in args:
  61. arg_string, arg_imports = serializer_factory(arg).serialize()
  62. strings.append(arg_string)
  63. imports.update(arg_imports)
  64. for kw, arg in sorted(kwargs.items()):
  65. arg_string, arg_imports = serializer_factory(arg).serialize()
  66. imports.update(arg_imports)
  67. strings.append("%s=%s" % (kw, arg_string))
  68. return "%s(%s)" % (name, ", ".join(strings)), imports
  69. @staticmethod
  70. def _serialize_path(path):
  71. module, name = path.rsplit(".", 1)
  72. if module == "django.db.models":
  73. imports = {"from django.db import models"}
  74. name = "models.%s" % name
  75. else:
  76. imports = {"import %s" % module}
  77. name = path
  78. return name, imports
  79. def serialize(self):
  80. return self.serialize_deconstructed(*self.value.deconstruct())
  81. class DictionarySerializer(BaseSerializer):
  82. def serialize(self):
  83. imports = set()
  84. strings = []
  85. for k, v in sorted(self.value.items()):
  86. k_string, k_imports = serializer_factory(k).serialize()
  87. v_string, v_imports = serializer_factory(v).serialize()
  88. imports.update(k_imports)
  89. imports.update(v_imports)
  90. strings.append((k_string, v_string))
  91. return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports
  92. class EnumSerializer(BaseSerializer):
  93. def serialize(self):
  94. enum_class = self.value.__class__
  95. module = enum_class.__module__
  96. v_string, v_imports = serializer_factory(self.value.value).serialize()
  97. imports = {'import %s' % module, *v_imports}
  98. return "%s.%s(%s)" % (module, enum_class.__name__, v_string), imports
  99. class FloatSerializer(BaseSimpleSerializer):
  100. def serialize(self):
  101. if math.isnan(self.value) or math.isinf(self.value):
  102. return 'float("{}")'.format(self.value), set()
  103. return super().serialize()
  104. class FrozensetSerializer(BaseSequenceSerializer):
  105. def _format(self):
  106. return "frozenset([%s])"
  107. class FunctionTypeSerializer(BaseSerializer):
  108. def serialize(self):
  109. if getattr(self.value, "__self__", None) and isinstance(self.value.__self__, type):
  110. klass = self.value.__self__
  111. module = klass.__module__
  112. return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {"import %s" % module}
  113. # Further error checking
  114. if self.value.__name__ == '<lambda>':
  115. raise ValueError("Cannot serialize function: lambda")
  116. if self.value.__module__ is None:
  117. raise ValueError("Cannot serialize function %r: No module" % self.value)
  118. module_name = self.value.__module__
  119. if '<' not in self.value.__qualname__: # Qualname can include <locals>
  120. return '%s.%s' % (module_name, self.value.__qualname__), {'import %s' % self.value.__module__}
  121. raise ValueError(
  122. 'Could not find function %s in %s.\n' % (self.value.__name__, module_name)
  123. )
  124. class FunctoolsPartialSerializer(BaseSerializer):
  125. def serialize(self):
  126. # Serialize functools.partial() arguments
  127. func_string, func_imports = serializer_factory(self.value.func).serialize()
  128. args_string, args_imports = serializer_factory(self.value.args).serialize()
  129. keywords_string, keywords_imports = serializer_factory(self.value.keywords).serialize()
  130. # Add any imports needed by arguments
  131. imports = {'import functools', *func_imports, *args_imports, *keywords_imports}
  132. return (
  133. 'functools.%s(%s, *%s, **%s)' % (
  134. self.value.__class__.__name__,
  135. func_string,
  136. args_string,
  137. keywords_string,
  138. ),
  139. imports,
  140. )
  141. class IterableSerializer(BaseSerializer):
  142. def serialize(self):
  143. imports = set()
  144. strings = []
  145. for item in self.value:
  146. item_string, item_imports = serializer_factory(item).serialize()
  147. imports.update(item_imports)
  148. strings.append(item_string)
  149. # When len(strings)==0, the empty iterable should be serialized as
  150. # "()", not "(,)" because (,) is invalid Python syntax.
  151. value = "(%s)" if len(strings) != 1 else "(%s,)"
  152. return value % (", ".join(strings)), imports
  153. class ModelFieldSerializer(DeconstructableSerializer):
  154. def serialize(self):
  155. attr_name, path, args, kwargs = self.value.deconstruct()
  156. return self.serialize_deconstructed(path, args, kwargs)
  157. class ModelManagerSerializer(DeconstructableSerializer):
  158. def serialize(self):
  159. as_manager, manager_path, qs_path, args, kwargs = self.value.deconstruct()
  160. if as_manager:
  161. name, imports = self._serialize_path(qs_path)
  162. return "%s.as_manager()" % name, imports
  163. else:
  164. return self.serialize_deconstructed(manager_path, args, kwargs)
  165. class OperationSerializer(BaseSerializer):
  166. def serialize(self):
  167. from django.db.migrations.writer import OperationWriter
  168. string, imports = OperationWriter(self.value, indentation=0).serialize()
  169. # Nested operation, trailing comma is handled in upper OperationWriter._write()
  170. return string.rstrip(','), imports
  171. class RegexSerializer(BaseSerializer):
  172. def serialize(self):
  173. regex_pattern, pattern_imports = serializer_factory(self.value.pattern).serialize()
  174. # Turn off default implicit flags (e.g. re.U) because regexes with the
  175. # same implicit and explicit flags aren't equal.
  176. flags = self.value.flags ^ re.compile('').flags
  177. regex_flags, flag_imports = serializer_factory(flags).serialize()
  178. imports = {'import re', *pattern_imports, *flag_imports}
  179. args = [regex_pattern]
  180. if flags:
  181. args.append(regex_flags)
  182. return "re.compile(%s)" % ', '.join(args), imports
  183. class SequenceSerializer(BaseSequenceSerializer):
  184. def _format(self):
  185. return "[%s]"
  186. class SetSerializer(BaseSequenceSerializer):
  187. def _format(self):
  188. # Serialize as a set literal except when value is empty because {}
  189. # is an empty dict.
  190. return '{%s}' if self.value else 'set(%s)'
  191. class SettingsReferenceSerializer(BaseSerializer):
  192. def serialize(self):
  193. return "settings.%s" % self.value.setting_name, {"from django.conf import settings"}
  194. class TupleSerializer(BaseSequenceSerializer):
  195. def _format(self):
  196. # When len(value)==0, the empty tuple should be serialized as "()",
  197. # not "(,)" because (,) is invalid Python syntax.
  198. return "(%s)" if len(self.value) != 1 else "(%s,)"
  199. class TypeSerializer(BaseSerializer):
  200. def serialize(self):
  201. special_cases = [
  202. (models.Model, "models.Model", []),
  203. (type(None), 'type(None)', []),
  204. ]
  205. for case, string, imports in special_cases:
  206. if case is self.value:
  207. return string, set(imports)
  208. if hasattr(self.value, "__module__"):
  209. module = self.value.__module__
  210. if module == builtins.__name__:
  211. return self.value.__name__, set()
  212. else:
  213. return "%s.%s" % (module, self.value.__name__), {"import %s" % module}
  214. class UUIDSerializer(BaseSerializer):
  215. def serialize(self):
  216. return "uuid.%s" % repr(self.value), {"import uuid"}
  217. class Serializer:
  218. _registry = OrderedDict([
  219. (frozenset, FrozensetSerializer),
  220. (list, SequenceSerializer),
  221. (set, SetSerializer),
  222. (tuple, TupleSerializer),
  223. (dict, DictionarySerializer),
  224. (enum.Enum, EnumSerializer),
  225. (datetime.datetime, DatetimeDatetimeSerializer),
  226. ((datetime.date, datetime.timedelta, datetime.time), DateTimeSerializer),
  227. (SettingsReference, SettingsReferenceSerializer),
  228. (float, FloatSerializer),
  229. ((bool, int, type(None), bytes, str, range), BaseSimpleSerializer),
  230. (decimal.Decimal, DecimalSerializer),
  231. ((functools.partial, functools.partialmethod), FunctoolsPartialSerializer),
  232. ((types.FunctionType, types.BuiltinFunctionType, types.MethodType), FunctionTypeSerializer),
  233. (collections.abc.Iterable, IterableSerializer),
  234. ((COMPILED_REGEX_TYPE, RegexObject), RegexSerializer),
  235. (uuid.UUID, UUIDSerializer),
  236. ])
  237. @classmethod
  238. def register(cls, type_, serializer):
  239. if not issubclass(serializer, BaseSerializer):
  240. raise ValueError("'%s' must inherit from 'BaseSerializer'." % serializer.__name__)
  241. cls._registry[type_] = serializer
  242. @classmethod
  243. def unregister(cls, type_):
  244. cls._registry.pop(type_)
  245. def serializer_factory(value):
  246. if isinstance(value, Promise):
  247. value = str(value)
  248. elif isinstance(value, LazyObject):
  249. # The unwrapped value is returned as the first item of the arguments
  250. # tuple.
  251. value = value.__reduce__()[1][0]
  252. if isinstance(value, models.Field):
  253. return ModelFieldSerializer(value)
  254. if isinstance(value, models.manager.BaseManager):
  255. return ModelManagerSerializer(value)
  256. if isinstance(value, Operation):
  257. return OperationSerializer(value)
  258. if isinstance(value, type):
  259. return TypeSerializer(value)
  260. # Anything that knows how to deconstruct itself.
  261. if hasattr(value, 'deconstruct'):
  262. return DeconstructableSerializer(value)
  263. for type_, serializer_cls in Serializer._registry.items():
  264. if isinstance(value, type_):
  265. return serializer_cls(value)
  266. raise ValueError(
  267. "Cannot serialize: %r\nThere are some values Django cannot serialize into "
  268. "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/"
  269. "topics/migrations/#migration-serializing" % (value, get_docs_version())
  270. )