Added support for serializing class methods. - Refs #21290.

The new handling allows us to do away with the whitelisting that was
required to support date and datetime objects.
This commit is contained in:
Loic Bistuer 2013-10-19 00:14:01 +07:00 committed by Tim Graham
parent 584110417f
commit 8d6953d55c
2 changed files with 5 additions and 12 deletions

View File

@ -148,18 +148,9 @@ class MigrationWriter(object):
return cls.serialize_deconstructed(path, args, kwargs) return cls.serialize_deconstructed(path, args, kwargs)
# Functions # Functions
elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)): elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
# Special-cases, as these don't have im_class # @classmethod?
special_cases = [ if getattr(value, "__self__", None) and isinstance(value.__self__, type):
(datetime.datetime.now, "datetime.datetime.now", ["import datetime"]), klass = value.__self__
(datetime.datetime.utcnow, "datetime.datetime.utcnow", ["import datetime"]),
(datetime.date.today, "datetime.date.today", ["import datetime"]),
]
for func, string, imports in special_cases:
if func == value: # For some reason "utcnow is not utcnow"
return string, set(imports)
# Method?
if hasattr(value, "im_class"):
klass = value.im_class
module = klass.__module__ module = klass.__module__
return "%s.%s.%s" % (module, klass.__name__, value.__name__), set(["import %s" % module]) return "%s.%s.%s" % (module, klass.__name__, value.__name__), set(["import %s" % module])
elif hasattr(value, 'deconstruct'): elif hasattr(value, 'deconstruct'):

View File

@ -73,6 +73,8 @@ class WriterTests(TestCase):
# Datetime stuff # Datetime stuff
self.assertSerializedEqual(datetime.datetime.utcnow()) self.assertSerializedEqual(datetime.datetime.utcnow())
self.assertSerializedEqual(datetime.datetime.utcnow) self.assertSerializedEqual(datetime.datetime.utcnow)
self.assertSerializedEqual(datetime.datetime.today())
self.assertSerializedEqual(datetime.datetime.today)
self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today())
self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.date.today)
# Django fields # Django fields