2020-10-16 16:55:33 +08:00
|
|
|
import datetime
|
2020-08-26 18:04:57 +08:00
|
|
|
import json
|
|
|
|
|
import pickle # nosec:B403
|
2020-10-16 16:55:33 +08:00
|
|
|
from decimal import Decimal
|
2020-08-26 18:04:57 +08:00
|
|
|
from typing import Any
|
|
|
|
|
|
2021-09-17 10:19:56 +08:00
|
|
|
import pendulum
|
2021-07-26 16:33:22 +08:00
|
|
|
from fastapi.encoders import jsonable_encoder
|
2020-10-16 16:55:33 +08:00
|
|
|
|
|
|
|
|
CONVERTERS = {
|
2021-09-17 10:19:56 +08:00
|
|
|
"date": pendulum.parse,
|
|
|
|
|
"datetime": lambda x: pendulum.parse(x, exact=True),
|
2020-10-16 16:55:33 +08:00
|
|
|
"decimal": Decimal,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonEncoder(json.JSONEncoder):
|
|
|
|
|
def default(self, obj):
|
|
|
|
|
if isinstance(obj, datetime.datetime):
|
2021-04-28 20:44:35 +03:00
|
|
|
if obj.tzinfo:
|
|
|
|
|
return {"val": obj.strftime("%Y-%m-%d %H:%M:%S%z"), "_spec_type": "datetime"}
|
|
|
|
|
else:
|
|
|
|
|
return {"val": obj.strftime("%Y-%m-%d %H:%M:%S"), "_spec_type": "datetime"}
|
2020-10-16 16:55:33 +08:00
|
|
|
elif isinstance(obj, datetime.date):
|
|
|
|
|
return {"val": obj.strftime("%Y-%m-%d"), "_spec_type": "date"}
|
|
|
|
|
elif isinstance(obj, Decimal):
|
|
|
|
|
return {"val": str(obj), "_spec_type": "decimal"}
|
|
|
|
|
else:
|
2021-01-11 03:11:35 -08:00
|
|
|
return jsonable_encoder(obj)
|
2020-10-16 16:55:33 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def object_hook(obj):
|
|
|
|
|
_spec_type = obj.get("_spec_type")
|
|
|
|
|
if not _spec_type:
|
|
|
|
|
return obj
|
|
|
|
|
|
|
|
|
|
if _spec_type in CONVERTERS:
|
|
|
|
|
return CONVERTERS[_spec_type](obj["val"])
|
|
|
|
|
else:
|
|
|
|
|
raise TypeError("Unknown {}".format(_spec_type))
|
|
|
|
|
|
2020-08-26 18:04:57 +08:00
|
|
|
|
|
|
|
|
class Coder:
|
|
|
|
|
@classmethod
|
|
|
|
|
def encode(cls, value: Any):
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def decode(cls, value: Any):
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonCoder(Coder):
|
|
|
|
|
@classmethod
|
|
|
|
|
def encode(cls, value: Any):
|
2020-10-16 16:55:33 +08:00
|
|
|
return json.dumps(value, cls=JsonEncoder)
|
2020-08-26 18:04:57 +08:00
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def decode(cls, value: Any):
|
2020-10-16 16:55:33 +08:00
|
|
|
return json.loads(value, object_hook=object_hook)
|
2020-08-26 18:04:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class PickleCoder(Coder):
|
|
|
|
|
@classmethod
|
|
|
|
|
def encode(cls, value: Any):
|
|
|
|
|
return pickle.dumps(value)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def decode(cls, value: Any):
|
|
|
|
|
return pickle.loads(value) # nosec:B403
|