mirror of
https://github.com/elisspace/core.git
synced 2026-10-06 01:06:26 +00:00
This was causing the wheels to fail to build. We need
to workout why when we don't have release pressure
This reverts commit d9d22a9556.
43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
"""Helpers to help with encoding Home Assistant objects in JSON."""
|
|
import datetime
|
|
import json
|
|
from typing import Any
|
|
|
|
|
|
class JSONEncoder(json.JSONEncoder):
|
|
"""JSONEncoder that supports Home Assistant objects."""
|
|
|
|
def default(self, o: Any) -> Any:
|
|
"""Convert Home Assistant objects.
|
|
|
|
Hand other objects to the original method.
|
|
"""
|
|
if isinstance(o, datetime.datetime):
|
|
return o.isoformat()
|
|
if isinstance(o, set):
|
|
return list(o)
|
|
if hasattr(o, "as_dict"):
|
|
return o.as_dict()
|
|
|
|
return json.JSONEncoder.default(self, o)
|
|
|
|
|
|
class ExtendedJSONEncoder(JSONEncoder):
|
|
"""JSONEncoder that supports Home Assistant objects and falls back to repr(o)."""
|
|
|
|
def default(self, o: Any) -> Any:
|
|
"""Convert certain objects.
|
|
|
|
Fall back to repr(o).
|
|
"""
|
|
if isinstance(o, datetime.timedelta):
|
|
return {"__type": str(type(o)), "total_seconds": o.total_seconds()}
|
|
if isinstance(o, datetime.datetime):
|
|
return o.isoformat()
|
|
if isinstance(o, (datetime.date, datetime.time)):
|
|
return {"__type": str(type(o)), "isoformat": o.isoformat()}
|
|
try:
|
|
return super().default(o)
|
|
except TypeError:
|
|
return {"__type": str(type(o)), "repr": repr(o)}
|