Skip to content

Commit 581302d

Browse files
authored
Merge pull request #57 from robotadam/remove-simplejson
Always handle Decimal objects in JSON
2 parents e91e5ac + c9953d2 commit 581302d

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

dwollav2/test/test_token.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import decimal
12
import unittest
23
import responses
34

@@ -163,3 +164,15 @@ def test_delete_with_headers_success(self):
163164
res = token.delete('foo', None, self.more_headers)
164165
self.assertEqual(200, res.status)
165166
self.assertEqual({'foo': 'bar'}, res.body)
167+
168+
@responses.activate
169+
def test_post_decimal(self):
170+
responses.add(responses.POST,
171+
self.client.api_url + '/foo',
172+
body='{"amount": "12.34"}',
173+
status=200,
174+
content_type='application/vnd.dwolla.v1.hal+json')
175+
token = self.client.Token(access_token=self.access_token)
176+
res = token.post('foo', body={'amount': decimal.Decimal('12.34')})
177+
self.assertEqual(200, res.status)
178+
self.assertEqual({'amount': '12.34'}, res.body)

dwollav2/token.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import requests
22
from io import IOBase
33
import re
4-
5-
try:
6-
import simplejson as json
7-
except ImportError:
8-
import json
4+
import json
5+
import decimal
96

107
from dwollav2.response import Response
118
from dwollav2.version import version
129

1310

11+
class DecimalEncoder(json.JSONEncoder):
12+
def default(self, o):
13+
if isinstance(o, decimal.Decimal):
14+
return str(o)
15+
return super().default(o)
16+
17+
1418
def _items_or_iteritems(o):
1519
try:
1620
return o.iteritems()
@@ -74,7 +78,7 @@ def post(self, url, body=None, headers={}, **kwargs):
7478
self._full_url(url),
7579
headers=self._merge_dicts(
7680
{'content-type': 'application/json'}, headers),
77-
data=json.dumps(body, sort_keys=True, indent=2),
81+
data=json.dumps(body, sort_keys=True, indent=2, cls=DecimalEncoder),
7882
**requests))
7983

8084
def get(self, url, params=None, headers={}, **kwargs):

0 commit comments

Comments
 (0)