Support for schema EnumField.

This commit is contained in:
Fabio Manganiello 2023-03-26 03:48:32 +02:00
parent 026662f6b6
commit 4b9c5a0203
Signed by: blacklight
GPG key ID: D90FBA7F76362774

View file

@ -1,5 +1,6 @@
from datetime import datetime, date
from typing import Optional, Union
from enum import Enum
from typing import Any, Optional, Type, Union
from dateutil.parser import isoparse
from dateutil.tz import tzutc
@ -66,6 +67,23 @@ class Date(Function): # lgtm [py/missing-call-to-init]
return date.fromtimestamp(dt.timestamp())
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
def normalize_datetime(
dt: Optional[Union[str, date, datetime]]
) -> Optional[Union[date, datetime]]: