From ba613c3410c5a0ff547e43d2e9cdd9ffff1fca54 Mon Sep 17 00:00:00 2001 From: Fred Drake Date: Thu, 10 Feb 2005 18:33:30 +0000 Subject: [PATCH] accept datetime.datetime instances when marshalling; dateTime.iso8601 elements still unmarshal into xmlrpclib.DateTime objects --- Lib/test/test_xmlrpc.py | 17 +++++++++++++++++ Lib/xmlrpclib.py | 17 ++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py index 1f533d206d7..8fa63de89fd 100644 --- a/Lib/test/test_xmlrpc.py +++ b/Lib/test/test_xmlrpc.py @@ -1,3 +1,4 @@ +import datetime import sys import unittest import xmlrpclib @@ -12,6 +13,11 @@ alist = [{'astring': 'foo@bar.baz.spam', 'boolean': xmlrpclib.False, 'unicode': u'\u4000\u6000\u8000', u'ukey\u4000': 'regular value', + 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), + 'datetime2': xmlrpclib.DateTime( + (2005, 02, 10, 11, 41, 23, 0, 1, -1)), + 'datetime3': xmlrpclib.DateTime( + datetime.datetime(2005, 02, 10, 11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): @@ -20,6 +26,17 @@ class XMLRPCTestCase(unittest.TestCase): self.assertEquals(alist, xmlrpclib.loads(xmlrpclib.dumps((alist,)))[0][0]) + def test_dump_bare_datetime(self): + # This checks that an unwrapped datetime object can be handled + # by the marshalling code. This can't be done via + # test_dump_load() since the unmarshaller doesn't produce base + # datetime instances. + dt = datetime.datetime(2005, 02, 10, 11, 41, 23) + s = xmlrpclib.dumps((dt,)) + r, m = xmlrpclib.loads(s) + self.assertEquals(r, (xmlrpclib.DateTime('20050210T11:41:23'),)) + self.assertEquals(m, None) + def test_dump_big_long(self): self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,)) diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py index 7b68196e3e5..21cc3d02ab4 100644 --- a/Lib/xmlrpclib.py +++ b/Lib/xmlrpclib.py @@ -148,6 +148,11 @@ try: except NameError: unicode = None # unicode support not available +try: + import datetime +except ImportError: + datetime = None + try: _bool_is_builtin = False.__class__.__name__ == "bool" except NameError: @@ -349,7 +354,10 @@ class DateTime: def __init__(self, value=0): if not isinstance(value, StringType): - if not isinstance(value, (TupleType, time.struct_time)): + if datetime and isinstance(value, datetime.datetime): + self.value = value.strftime("%Y%m%dT%H:%M:%S") + return + elif not isinstance(value, (TupleType, time.struct_time)): if value == 0: value = time.time() value = time.localtime(value) @@ -699,6 +707,13 @@ class Marshaller: del self.memo[i] dispatch[DictType] = dump_struct + if datetime: + def dump_datetime(self, value, write): + write("") + write(value.strftime("%Y%m%dT%H:%M:%S")) + write("\n") + dispatch[datetime.datetime] = dump_datetime + def dump_instance(self, value, write): # check for special wrappers if value.__class__ in WRAPPERS: