Support for decimal.Decimal type JSON serialization

This commit is contained in:
Fabio Manganiello 2022-10-29 13:35:52 +02:00
parent 486cd66885
commit cdacf50fc7
Signed by: blacklight
GPG Key ID: D90FBA7F76362774
1 changed files with 20 additions and 13 deletions

View File

@ -1,4 +1,5 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import decimal
import datetime import datetime
import logging import logging
import inspect import inspect
@ -19,7 +20,7 @@ class JSONAble(ABC):
raise NotImplementedError() raise NotImplementedError()
class Message(object): class Message:
""" """
Message generic class Message generic class
""" """
@ -38,6 +39,8 @@ class Message(object):
return int(obj) return int(obj)
if isinstance(obj, np.ndarray): if isinstance(obj, np.ndarray):
return obj.tolist() return obj.tolist()
if isinstance(obj, decimal.Decimal):
return float(obj)
if callable(obj): if callable(obj):
return '<function at {}.{}>'.format(obj.__module__, obj.__name__) return '<function at {}.{}>'.format(obj.__module__, obj.__name__)
@ -45,9 +48,7 @@ class Message(object):
@staticmethod @staticmethod
def parse_datetime(obj): def parse_datetime(obj):
if isinstance(obj, datetime.datetime) or \ if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
isinstance(obj, datetime.date) or \
isinstance(obj, datetime.time):
return obj.isoformat() return obj.isoformat()
def default(self, obj): def default(self, obj):
@ -68,8 +69,11 @@ class Message(object):
try: try:
return super().default(obj) return super().default(obj)
except Exception as e: except Exception as e:
logger.warning('Could not serialize object type {}: {}: {}'.format( logger.warning(
type(obj), str(e), obj)) 'Could not serialize object type {}: {}: {}'.format(
type(obj), str(e), obj
)
)
def __init__(self, timestamp=None, *_, **__): def __init__(self, timestamp=None, *_, **__):
self.timestamp = timestamp or time.time() self.timestamp = timestamp or time.time()
@ -80,12 +84,15 @@ class Message(object):
the message into a UTF-8 JSON string the message into a UTF-8 JSON string
""" """
return json.dumps({ return json.dumps(
attr: getattr(self, attr) {
for attr in self.__dir__() attr: getattr(self, attr)
if (attr != '_timestamp' or not attr.startswith('_')) for attr in self.__dir__()
and not inspect.ismethod(getattr(self, attr)) if (attr != '_timestamp' or not attr.startswith('_'))
}, cls=self.Encoder).replace('\n', ' ') and not inspect.ismethod(getattr(self, attr))
},
cls=self.Encoder,
).replace('\n', ' ')
def __bytes__(self): def __bytes__(self):
""" """
@ -105,7 +112,7 @@ class Message(object):
if isinstance(msg, cls): if isinstance(msg, cls):
msg = str(msg) msg = str(msg)
if isinstance(msg, bytes) or isinstance(msg, bytearray): if isinstance(msg, (bytes, bytearray)):
msg = msg.decode('utf-8') msg = msg.decode('utf-8')
if isinstance(msg, str): if isinstance(msg, str):
try: try: