Skip to content

Extend JSONEncoder with datetime, date, time & UUID #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions basecrm/http_client.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,44 @@
import datetime
import decimal
import uuid

import requests
import json


from munch import munchify
from decimal import *

from basecrm.errors import RateLimitError, RequestError, ResourceError, ServerError

class DecimalEncoder(json.JSONEncoder):

class ExtendedJSONEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time, decimal types, and
UUIDs.

Borrowed from https://github.com/django/django/blob/main/django/core/serializers/json.py#L77
"""

def default(self, o):
if isinstance(o, Decimal):
return float(o)
super(DecimalEncoder, self).default(o)
# See "Date Time String Format" in the ECMA-262 specification.
if isinstance(o, datetime.datetime):
r = o.isoformat()
if o.microsecond:
r = r[:23] + r[26:]
if r.endswith("+00:00"):
r = r[:-6] + "Z"
return r
elif isinstance(o, datetime.date):
return o.isoformat()
elif isinstance(o, datetime.time):
r = o.isoformat()
if o.microsecond:
r = r[:12]
return r
elif isinstance(o, (decimal.Decimal, uuid.UUID)):
return str(o)
else:
return super().default(o)


class HttpClient(object):
Expand Down Expand Up @@ -132,7 +159,7 @@ def request(self, method, url, params=None, body=None, **kwargs):
if body is not None:
headers['Content-Type'] = 'application/json'
payload = body if raw else self.wrap_envelope(body)
body = json.dumps(self.wrap_envelope(body), cls=DecimalEncoder)
body = json.dumps(self.wrap_envelope(body), cls=ExtendedJSONEncoder)

resp = requests.request(method, url,
params=params,
Expand Down