[jsonutils] Add handling of datetime.date format

Recent patch from keystone[1] do not work when
osprofiler is enabled as osprofiler does jsonutils.dumps
and datetime.date is not handled so it fails.
This patch adds the handling for it.

[1] https://review.opendev.org/c/openstack/keystone/+/924892

Needed-By: https://review.opendev.org/q/I1b71fb3881dc041db01083fbb4f2592400096a31
Related-Bug: #2074018
Closes-Bug: #2076430
Change-Id: Ifbcf5a1b3d42516bdf73f7ca6b2a7338f3985283
(cherry picked from commit f6e879db55)
This commit is contained in:
yatinkarel 2024-08-13 11:35:05 +05:30 committed by yatin
parent aa0b8bfb68
commit b7c9063a9b
2 changed files with 17 additions and 0 deletions

View File

@ -43,6 +43,8 @@ from oslo_utils import encodeutils
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import timeutils from oslo_utils import timeutils
_ISO8601_DATE_FORMAT = '%Y-%m-%d'
ipaddress = importutils.try_import("ipaddress") ipaddress = importutils.try_import("ipaddress")
netaddr = importutils.try_import("netaddr") netaddr = importutils.try_import("netaddr")
@ -117,6 +119,12 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
else: else:
return value return value
if isinstance(value, datetime.date):
if convert_datetime:
return value.strftime(_ISO8601_DATE_FORMAT)
else:
return value
if isinstance(value, uuid.UUID): if isinstance(value, uuid.UUID):
return str(value) return str(value)

View File

@ -159,6 +159,15 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7) x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7)
self.assertEqual(x, jsonutils.to_primitive(x, convert_datetime=False)) self.assertEqual(x, jsonutils.to_primitive(x, convert_datetime=False))
def test_date(self):
x = datetime.date(1920, 2, 3)
self.assertEqual('1920-02-03',
jsonutils.to_primitive(x))
def test_date_preserve(self):
x = datetime.date(1920, 2, 3)
self.assertEqual(x, jsonutils.to_primitive(x, convert_datetime=False))
def test_DateTime(self): def test_DateTime(self):
x = xmlrpclib.DateTime() x = xmlrpclib.DateTime()
x.decode("19710203T04:05:06") x.decode("19710203T04:05:06")