kerno.web.to_dict module¶
A setup so you can have many, powerful to_dict() implementations.
Our main objective is to remove any JSON concerns from model classes.
These should NOT contain as_dict()
implementations because the system
may need multiple converters for the same model – for instance,
with varying fields, verbosities, levels of detail,
optional inclusion of related entities etc.
It is bad if AVerySpecificModel.as_dict() needs a different signature to accept a parameter that all the other as_dict() methods do not need.
Here is the solution:
By using Reg we now have a
to_dict(obj, flavor='', **kw)
function that dispatches
on the type of obj
and flavor
. This allows you to register
more than one implementation (with a “flavor” name) for each of your
model classes.
In order to understand this, you need to know what Reg does: multiple dispatch.
Our to_dict() function also has a default implementation, so it can be used directly.
This way you can create a situation in which:
to_dict(Address, flavor="") # calls one implementation, and
to_dict(Person, flavor="") # calls another implementation, and
to_dict(Person, flavor="table") # calls yet another implementation.
If the user code omits the flavor argument, the default one – whose value is an empty string – gets used.
And because our to_dict()
accepts keyword arguments, you can create
a very powerful version of it, that can take such arguments as
a repository, a user object, the current date etc.
Please see a usage example in our tests.
- kerno.web.to_dict.keys_from(obj: Any) Iterable [source]¶
Return the names of the instance variables of
obj
.
- kerno.web.to_dict.only_relevant(keys: Iterable[str]) Iterable[str] [source]¶
Ignore strings that start in dunder (“__”) or in “_sa_”.
These are usually keeping SQLAlchemy state.
- kerno.web.to_dict.reuse_dict(obj: Any, keys: Iterable = (), for_json: bool = True, sort: bool = True, **kw) collections.OrderedDict [source]¶
Dump the instance variables of
obj
into an OrderedDict.This function is reusable and free of Reg dispatch.
If the
for_json
flag is True, convert certain types.If the
sort
flag is True, sort the OrderedDict.