From f2b3000922f92e1b805579c66c389c68d13f29ef Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Sat, 14 Mar 2020 18:35:45 +0100 Subject: [PATCH] Handle numpy types in the JSON message encoder --- platypush/message/__init__.py | 28 +++++++++++++++++++++++++++- platypush/message/event/__init__.py | 2 +- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/platypush/message/__init__.py b/platypush/message/__init__.py index f341e372..d55d45a4 100644 --- a/platypush/message/__init__.py +++ b/platypush/message/__init__.py @@ -11,15 +11,41 @@ class Message(object): """ Message generic class """ class Encoder(json.JSONEncoder): - def default(self, obj): + @staticmethod + def parse_numpy(obj): + try: + import numpy as np + except ImportError: + return + + if isinstance(obj, np.floating): + return float(obj) + if isinstance(obj, np.integer): + return int(obj) + if isinstance(obj, np.ndarray): + return obj.tolist() + + return + + @staticmethod + def parse_datetime(obj): if isinstance(obj, datetime.datetime) or \ isinstance(obj, datetime.date) or \ isinstance(obj, datetime.time): return obj.isoformat() + def default(self, obj): + value = self.parse_datetime(obj) + if value is not None: + return value + if isinstance(obj, set): return list(obj) + value = self.parse_numpy(obj) + if value is not None: + return value + return super().default(obj) def __init__(self, timestamp=None, *args, **kwargs): diff --git a/platypush/message/event/__init__.py b/platypush/message/event/__init__.py index 037a9e9d..966e16e4 100644 --- a/platypush/message/event/__init__.py +++ b/platypush/message/event/__init__.py @@ -182,7 +182,7 @@ class Event(Message): 'type': self.type, **args }, - }) + }, cls=self.Encoder) class EventMatchResult(object):