Skip to content

Commit

Permalink
Apply suggestions from code review
Browse files Browse the repository at this point in the history
Co-authored-by: ivan-klass <klass.ivanklass@gmail.com>
  • Loading branch information
Mogost and ivan-klass authored Aug 16, 2024
1 parent fd5b5ab commit fe50e54
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions constance/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,28 @@

logger = logging.getLogger(__name__)

DEFAULT_MARKER = 'default'
DEFAULT_DISCRIMINATOR = 'default'


class JSONEncoder(json.JSONEncoder):
"""Django-constance custom json encoder."""

def default(self, o):
for marker, (t, _, encoder) in _codecs.items():
for discriminator, (t, _, encoder) in _codecs.items():
if isinstance(o, t):
return _as(marker, encoder(o))
return _as(discriminator, encoder(o))
raise TypeError(f'Object of type {o.__class__.__name__} is not JSON serializable')


def _as(t: str, v: Any) -> dict[str, Any]:
return {'__type__': t, '__value__': v}
def _as(discriminator: str, v: Any) -> dict[str, Any]:
return {'__type__': discriminator, '__value__': v}


def dumps(obj, _dumps=json.dumps, cls=JSONEncoder, default_kwargs=None, **kwargs):
"""Serialize object to json string."""
default_kwargs = default_kwargs or {}
is_default_type = isinstance(obj, (str, int, bool, float, type(None)))
return _dumps(_as(DEFAULT_MARKER, obj) if is_default_type else obj, cls=cls, **dict(default_kwargs, **kwargs))
return _dumps(_as(DEFAULT_DISCRIMINATOR, obj) if is_default_type else obj, cls=cls, **dict(default_kwargs, **kwargs))


def loads(s, _loads=json.loads, **kwargs):
Expand Down Expand Up @@ -69,12 +69,12 @@ class Decoder(Protocol[T]):
def __call__(self, value: str, /) -> T: ...


def register_type(t: type[T], marker: str, encoder: Encoder[T], decoder: Decoder[T]):
def register_type(t: type[T], discriminator: str, encoder: Encoder[T], decoder: Decoder[T]):
if not marker:
raise ValueError('Marker must be specified')
if _codecs.get(marker) or marker == DEFAULT_MARKER:
raise ValueError(f'Type with marker {marker} is already registered')
_codecs[marker] = (t, decoder, encoder)
raise ValueError('Discriminator must be specified')
if _codecs.get(discriminator) or discriminator == DEFAULT_MARKER:
raise ValueError(f'Type with discriminator {discriminator} is already registered')
_codecs[discriminator] = (t, decoder, encoder)


_codecs: dict[str, tuple[type, Decoder, Encoder]] = {}
Expand Down

0 comments on commit fe50e54

Please sign in to comment.