Register mopidy models for deserialization.
All from ValidatedImmutableObject derived classes are registered for automatically deserialization by model_json_decoder().
This commit is contained in:
parent
3eac589557
commit
58db550bd6
@ -4,9 +4,6 @@ from mopidy.internal import validation
|
||||
from mopidy.models import Ref, TlTrack, fields
|
||||
from mopidy.models.immutable import ValidatedImmutableObject
|
||||
|
||||
_MODELS = ['HistoryTrack', 'HistoryState', 'MixerState', 'PlaybackState',
|
||||
'TracklistState', 'CoreState']
|
||||
|
||||
|
||||
class HistoryTrack(ValidatedImmutableObject):
|
||||
"""
|
||||
|
||||
@ -8,6 +8,10 @@ from mopidy.internal import deprecation
|
||||
from mopidy.models.fields import Field
|
||||
|
||||
|
||||
# Registered models for automatic deserialization
|
||||
_models = {}
|
||||
|
||||
|
||||
class ImmutableObject(object):
|
||||
"""
|
||||
Superclass for immutable objects whose fields can only be modified via the
|
||||
@ -150,9 +154,14 @@ class _ValidatedImmutableObjectMeta(type):
|
||||
attrs['_instances'] = weakref.WeakValueDictionary()
|
||||
attrs['__slots__'] = list(attrs.get('__slots__', [])) + fields.values()
|
||||
|
||||
return super(_ValidatedImmutableObjectMeta, cls).__new__(
|
||||
clsc = super(_ValidatedImmutableObjectMeta, cls).__new__(
|
||||
cls, name, bases, attrs)
|
||||
|
||||
if clsc.__name__ != 'ValidatedImmutableObject':
|
||||
_models[clsc.__name__] = clsc
|
||||
|
||||
return clsc
|
||||
|
||||
def __call__(cls, *args, **kwargs): # noqa: N805
|
||||
instance = super(_ValidatedImmutableObjectMeta, cls).__call__(
|
||||
*args, **kwargs)
|
||||
|
||||
@ -4,8 +4,6 @@ import json
|
||||
|
||||
from mopidy.models import immutable
|
||||
|
||||
_MODELS = ['Ref', 'Artist', 'Album', 'Track', 'TlTrack', 'Playlist']
|
||||
|
||||
|
||||
class ModelJSONEncoder(json.JSONEncoder):
|
||||
|
||||
@ -40,11 +38,8 @@ def model_json_decoder(dct):
|
||||
|
||||
"""
|
||||
if '__model__' in dct:
|
||||
from mopidy import models
|
||||
model_name = dct.pop('__model__')
|
||||
if model_name in _MODELS:
|
||||
return getattr(models, model_name)(**dct)
|
||||
from mopidy import internal
|
||||
if model_name in internal.models._MODELS:
|
||||
return getattr(internal.models, model_name)(**dct)
|
||||
if model_name in immutable._models:
|
||||
cls = immutable._models[model_name]
|
||||
return cls(**dct)
|
||||
return dct
|
||||
|
||||
Loading…
Reference in New Issue
Block a user