forked from platypush/platypush
Support dataclass serialization in the standard message serializer.
This commit is contained in:
parent
dc3392c11d
commit
6711b26137
1 changed files with 6 additions and 4 deletions
|
@ -1,4 +1,5 @@
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
from dataclasses import asdict, is_dataclass
|
||||||
import decimal
|
import decimal
|
||||||
import datetime
|
import datetime
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
@ -77,6 +78,9 @@ class Message:
|
||||||
if isinstance(obj, Enum):
|
if isinstance(obj, Enum):
|
||||||
return obj.value
|
return obj.value
|
||||||
|
|
||||||
|
if is_dataclass(obj):
|
||||||
|
obj = asdict(obj)
|
||||||
|
|
||||||
# Don't serialize I/O wrappers/objects
|
# Don't serialize I/O wrappers/objects
|
||||||
if isinstance(obj, io.IOBase):
|
if isinstance(obj, io.IOBase):
|
||||||
return None
|
return None
|
||||||
|
@ -85,9 +89,7 @@ class Message:
|
||||||
return super().default(obj)
|
return super().default(obj)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
'Could not serialize object type {}: {}: {}'.format(
|
'Could not serialize object type %s: %s: %s', type(obj), e, obj
|
||||||
type(obj), str(e), obj
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def __init__(self, *_, timestamp=None, logging_level=logging.INFO, **__):
|
def __init__(self, *_, timestamp=None, logging_level=logging.INFO, **__):
|
||||||
|
@ -152,7 +154,7 @@ class Message:
|
||||||
try:
|
try:
|
||||||
msg = json.loads(msg.strip())
|
msg = json.loads(msg.strip())
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
logger.warning('Invalid JSON message: {}'.format(msg))
|
logger.warning('Invalid JSON message: %s', msg)
|
||||||
|
|
||||||
assert isinstance(msg, dict)
|
assert isinstance(msg, dict)
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue