Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_get_offset_str(self):
dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34,
tzinfo=datetime.timezone.utc)
td = datetime.timedelta(hours=3)
dat2 = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34,
tzinfo=datetime.timezone(td))
offset_str_dat = get_offset_str(dat, StateHolder)
offset_str_dat2 = get_offset_str(dat2, StateHolder)
offset_str_td = get_offset_str(td, StateHolder)
self.assertEqual('Z', offset_str_dat)
self.assertEqual('+03:00', offset_str_dat2)
self.assertEqual('+03:00', offset_str_td)
def announce_class(
cls: type,
cls_name: Optional[str] = None,
fork_inst: type = StateHolder):
"""
Announce the given cls to jsons to allow jsons to deserialize a verbose
dump into that class.
:param cls: the class that is to be announced.
:param cls_name: a custom name for that class.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
:return: None.
"""
cls_name = cls_name or get_class_name(cls, fully_qualified=True)
fork_inst._announced_classes[cls] = cls_name
fork_inst._announced_classes[cls_name] = cls
def set_serializer(
func: callable,
cls: Union[type, Sequence[type]],
high_prio: bool = True,
fork_inst: type = StateHolder) -> None:
"""
Set a serializer function for the given type. You may override the default
behavior of ``jsons.load`` by setting a custom serializer.
The ``func`` argument must take one argument (i.e. the object that is to be
serialized) and also a ``kwargs`` parameter. For example:
>>> def func(obj, **kwargs):
... return dict()
You may ask additional arguments between ``cls`` and ``kwargs``.
:param func: the serializer function.
:param cls: the type or sequence of types this serializer can handle.
:param high_prio: determines the order in which is looked for the callable.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
def get_class_name(cls: type,
transformer: Optional[Callable[[str], str]] = None,
fully_qualified: bool = False,
fork_inst: Optional[type] = StateHolder) -> Optional[str]:
"""
Return the name of a class.
:param cls: the class of which the name if to be returned.
:param transformer: any string transformer, e.g. ``str.lower``.
:param fully_qualified: if ``True`` return the fully qualified name (i.e.
complete with module name).
:param fork_inst if given, it uses this fork of ``JsonSerializable`` for
finding the class name.
:return: the name of ``cls``, transformed if a transformer is given.
"""
transformer = transformer or (lambda x: x)
cls_name = _get_special_cases(cls)
if cls_name:
return transformer(cls_name)
if cls in fork_inst._announced_classes:
return transformer(fork_inst._announced_classes[cls])
def get_serializer(
cls: type,
fork_inst: Optional[type] = StateHolder) -> callable:
"""
Return the serializer function that would be used for the given ``cls``.
:param cls: the type for which a serializer is to be returned.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
:return: a serializer function.
"""
serializer = _get_lizer(cls, fork_inst._serializers,
fork_inst._classes_serializers, fork_inst)
return serializer
def dump(obj: object,
cls: Optional[type] = None,
fork_inst: Optional[type] = StateHolder,
**kwargs) -> object:
"""
Serialize the given ``obj`` to a JSON equivalent type (e.g. dict, list,
int, ...).
The way objects are serialized can be finetuned by setting serializer
functions for the specific type using ``set_serializer``.
You can also provide ``cls`` to specify that ``obj`` needs to be serialized
as if it was of type ``cls`` (meaning to only take into account attributes
from ``cls``). The type ``cls`` must have a ``__slots__`` defined. Any type
will do, but in most cases you may want ``cls`` to be a base class of
``obj``.
:param obj: a Python instance of any sort.
:param cls: if given, ``obj`` will be dumped as if it is of type ``type``.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
from typing import Optional
from jsons._common_impl import get_class_name, StateHolder
from jsons._dump_impl import dump, dumps, dumpb
from jsons._lizers_impl import set_serializer, set_deserializer
from jsons._load_impl import load, loads, loadb
class JsonSerializable(StateHolder):
"""
This class offers an alternative to using the ``jsons.load`` and
``jsons.dump`` methods. An instance of a class that inherits from
``JsonSerializable`` has the ``json`` property, which value is equivalent
to calling ``jsons.dump`` on that instance. Furthermore, you can call
``from_json`` on that class, which is equivalent to calling ``json.load``
with that class as an argument.
"""
_fork_counter = 0
@classmethod
def fork(cls, name: Optional[str] = None) -> type:
"""
Create a 'fork' of ``JsonSerializable``: a new ``type`` with a separate
configuration of serializers and deserializers.
:param name: the ``__name__`` of the new ``type``.
def suppress_warnings(
do_suppress: Optional[bool] = True,
fork_inst: Optional[type] = StateHolder):
"""
Suppress (or stop suppressing) warnings.
:param do_suppress: if ``True``, warnings will be suppressed from now on.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
:return: None.
"""
fork_inst._suppress_warnings = do_suppress
def default_object_serializer(
obj: object,
cls: Optional[type] = None,
*,
key_transformer: Optional[Callable[[str], str]] = None,
strip_nulls: bool = False,
strip_privates: bool = False,
strip_properties: bool = False,
strip_class_variables: bool = False,
strip_attr: Union[str, MutableSequence[str], Tuple[str]] = None,
verbose: Union[Verbosity, bool] = False,
strict: bool = False,
fork_inst: Optional[type] = StateHolder,
**kwargs) -> Optional[dict]:
"""
Serialize the given ``obj`` to a dict. All values within ``obj`` are also
serialized. If ``key_transformer`` is given, it will be used to transform
the casing (e.g. snake_case) to a different format (e.g. camelCase).
:param obj: the object that is to be serialized.
:param cls: the type of the object that is to be dumped.
:param key_transformer: a function that will be applied to all keys in the
resulting dict.
:param strip_nulls: if ``True`` the resulting dict will not contain null
values.
:param strip_privates: if ``True`` the resulting dict will not contain
private attributes (i.e. attributes that start with an underscore).
:param strip_properties: if ``True`` the resulting dict will not contain
values from @properties.
:param strip_class_variables: if ``True`` the resulting dict will not
def validate(
obj: object,
cls: type,
fork_inst: type = StateHolder) -> None:
"""
Validate the given ``obj`` with the validator that was registered for
``cls``. Raises a ``ValidationError`` if the validation failed.
:param obj: the object that is to be validated.
:param cls: the type of which the validator function was registered.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
:return: None.
"""
validator = get_validator(cls, fork_inst)
result = True
msg = 'Validation failed.'
if validator:
try:
result = validator(obj)
except Exception as err:
if err.args: