From 2fc4042fd22b2dff35418d599db167366f624a7b Mon Sep 17 00:00:00 2001 From: Steve Heyman Date: Mon, 16 Feb 2015 13:05:16 -0600 Subject: [PATCH] Fix serialization of datetime objects json.dumps needs a custom default function to handle the case of serializing a datetime object with an embedded Utc object. This CR adds a generic method to allow anyone needed to perform such special processing to include it all in one place. Change-Id: I84a31e38bf97d83a62108d8cb8f0466ed7fc7d03 Closes-Bug: 1420442 --- barbicanclient/client.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/barbicanclient/client.py b/barbicanclient/client.py index d4da6560..0dcbc588 100644 --- a/barbicanclient/client.py +++ b/barbicanclient/client.py @@ -159,11 +159,34 @@ class Client(object): resp = self._session.delete(href, headers=headers, json=json) self._check_status_code(resp) + def _deserialization_helper(self, obj): + """ + Help deserialization of objects which may require special processing + (for example datetime objects). If your object gives you + json.dumps errors when you attempt to deserialize then this + function is the place where you will handle that special case. + + :param obj: an object that may or may not require special processing + :return: the stringified object (if it required special processing) or + the object itself. + """ + # by default, return the object itself + return_str = obj + + # special case for objects that contain isoformat method (ie datetime) + if hasattr(obj, 'isoformat'): + return_str = obj.isoformat() + + return return_str + def _post(self, path, data): url = '{0}/{1}/'.format(self._base_url, path) headers = {'Content-Type': 'application/json'} headers.update(self._default_headers) - resp = self._session.post(url, data=json.dumps(data), headers=headers) + resp = self._session.post( + url, + data=json.dumps(data, default=self._deserialization_helper), + headers=headers) self._check_status_code(resp) return resp.json()