2021-10-26 00:48:05 +02:00
|
|
|
from datetime import datetime, date
|
2023-03-26 03:48:32 +02:00
|
|
|
from enum import Enum
|
|
|
|
from typing import Any, Optional, Type, Union
|
2021-07-22 01:02:15 +02:00
|
|
|
|
2021-10-01 23:50:53 +02:00
|
|
|
from dateutil.parser import isoparse
|
|
|
|
from dateutil.tz import tzutc
|
2021-07-28 01:09:09 +02:00
|
|
|
from marshmallow import fields
|
|
|
|
|
|
|
|
|
2022-07-23 17:32:14 +02:00
|
|
|
class StrippedString(fields.Function): # lgtm [py/missing-call-to-init]
|
2021-07-28 01:09:09 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['serialize'] = self._strip
|
|
|
|
kwargs['deserialize'] = self._strip
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2021-10-26 00:48:05 +02:00
|
|
|
def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:
|
|
|
|
if obj.get(attr) is not None:
|
|
|
|
return self._strip(obj.get(attr))
|
|
|
|
|
2021-07-28 01:09:09 +02:00
|
|
|
@staticmethod
|
|
|
|
def _strip(value: str):
|
|
|
|
return value.strip()
|
|
|
|
|
2021-07-22 01:02:15 +02:00
|
|
|
|
2022-07-23 17:32:14 +02:00
|
|
|
class Function(fields.Function): # lgtm [py/missing-call-to-init]
|
2022-08-28 11:55:30 +02:00
|
|
|
def _get_attr(self, obj, attr: str, _recursive=True):
|
|
|
|
if self.attribute and _recursive:
|
|
|
|
return self._get_attr(obj, self.attribute, False)
|
2022-07-23 17:32:14 +02:00
|
|
|
if hasattr(obj, attr):
|
|
|
|
return getattr(obj, attr)
|
|
|
|
elif hasattr(obj, 'get'):
|
|
|
|
return obj.get(attr)
|
|
|
|
|
|
|
|
|
|
|
|
class DateTime(Function): # lgtm [py/missing-call-to-init]
|
2021-10-01 23:50:53 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.metadata = {
|
|
|
|
'example': datetime.now(tz=tzutc()).isoformat(),
|
|
|
|
**(self.metadata or {}),
|
|
|
|
}
|
|
|
|
|
|
|
|
def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:
|
2022-07-23 17:32:14 +02:00
|
|
|
value = normalize_datetime(self._get_attr(obj, attr))
|
2021-10-01 23:50:53 +02:00
|
|
|
if value:
|
|
|
|
return value.isoformat()
|
|
|
|
|
|
|
|
def _deserialize(self, value, attr, data, **kwargs) -> Optional[datetime]:
|
|
|
|
return normalize_datetime(value)
|
|
|
|
|
|
|
|
|
2022-07-23 17:32:14 +02:00
|
|
|
class Date(Function): # lgtm [py/missing-call-to-init]
|
2021-10-26 00:48:05 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.metadata = {
|
|
|
|
'example': date.today().isoformat(),
|
|
|
|
**(self.metadata or {}),
|
|
|
|
}
|
|
|
|
|
|
|
|
def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:
|
2022-07-23 17:32:14 +02:00
|
|
|
value = normalize_datetime(self._get_attr(obj, attr))
|
2021-10-26 00:48:05 +02:00
|
|
|
if value:
|
|
|
|
return date(value.year, value.month, value.day).isoformat()
|
|
|
|
|
|
|
|
def _deserialize(self, value, attr, data, **kwargs) -> Optional[date]:
|
|
|
|
dt = normalize_datetime(value)
|
|
|
|
return date.fromtimestamp(dt.timestamp())
|
|
|
|
|
|
|
|
|
2023-03-26 03:48:32 +02:00
|
|
|
class EnumField(Function):
|
|
|
|
"""
|
|
|
|
Field that maps enum values.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# pylint: disable=redefined-builtin
|
|
|
|
def __init__(self, *args, type: Type[Enum], **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.type = type
|
|
|
|
|
|
|
|
def _serialize(self, value: Optional[Enum], *_, **__) -> Optional[Any]:
|
|
|
|
return value.value if value is not None else None
|
|
|
|
|
|
|
|
def _deserialize(self, value: Optional[Any], *_, **__) -> Optional[Any]:
|
|
|
|
return self.type(value) if value is not None else None
|
|
|
|
|
|
|
|
|
2022-07-23 17:32:14 +02:00
|
|
|
def normalize_datetime(
|
|
|
|
dt: Optional[Union[str, date, datetime]]
|
|
|
|
) -> Optional[Union[date, datetime]]:
|
2021-07-22 01:02:15 +02:00
|
|
|
if not dt:
|
|
|
|
return
|
2022-07-23 17:32:14 +02:00
|
|
|
if isinstance(dt, (datetime, date)):
|
2021-10-01 23:50:53 +02:00
|
|
|
return dt
|
2021-10-26 00:48:05 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
dt = float(dt)
|
|
|
|
return datetime.fromtimestamp(dt)
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
return isoparse(dt)
|