Skip to content

Commit

Permalink
Merge pull request #375 from stripe/ob-repr-datetime
Browse files Browse the repository at this point in the history
Use custom JSON encoder to handle datetime objects
  • Loading branch information
ob-stripe authored Nov 29, 2017
2 parents 204cc08 + 7bfd74b commit 3e29def
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
10 changes: 9 additions & 1 deletion stripe/stripe_object.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import, division, print_function

import datetime
import warnings
from copy import deepcopy

Expand Down Expand Up @@ -33,6 +34,12 @@ def _serialize_list(array, previous):


class StripeObject(dict):
class ReprJSONEncoder(util.json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return api_requestor._encode_datetime(obj)
return super(StripeObject.ReprJSONEncoder, self).default(obj)

def __init__(self, id=None, api_key=None, stripe_version=None,
stripe_account=None, **params):
super(StripeObject, self).__init__()
Expand Down Expand Up @@ -212,7 +219,8 @@ def __repr__(self):
return unicode_repr

def __str__(self):
return util.json.dumps(self, sort_keys=True, indent=2)
return util.json.dumps(self, sort_keys=True, indent=2,
cls=self.ReprJSONEncoder)

def to_dict(self):
warnings.warn(
Expand Down
3 changes: 3 additions & 0 deletions tests/test_stripe_object.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import, division, print_function

import datetime
import pickle
from copy import copy, deepcopy

Expand Down Expand Up @@ -178,6 +179,7 @@ def test_repr(self):
'foo', 'bar', myparam=5)

obj['object'] = u'\u4e00boo\u1f00'
obj.date = datetime.datetime.fromtimestamp(1511136000)

res = repr(obj)

Expand All @@ -186,6 +188,7 @@ def test_repr(self):

self.assertTrue(u'<StripeObject \u4e00boo\u1f00' in res)
self.assertTrue(u'id=foo' in res)
self.assertTrue(u'"date": 1511136000' in res)

def test_pickling(self):
obj = stripe.stripe_object.StripeObject(
Expand Down

0 comments on commit 3e29def

Please sign in to comment.