This is basically sommething like JSON-schema, but it works with static type checking, since the classes you define are just regular python dataclasse

monomonedula / nvelope Public

submited by
Style Pass
2021-11-25 21:30:03

This is basically sommething like JSON-schema, but it works with static type checking, since the classes you define are just regular python dataclasses which can (and should) be type checked with mypy library.

It also lets not to just define the structure of your JSON data in a single place in your python code, but also to define custom checks and conversions from/to JSON for any type you want.

You may define a shared package with the messages definition and use the model's .as_json() method on one end to serialize the message and .from_json() on the other to convert it into a DTO, checking and modifying the fields and their values along the way exactly how you defined it in a single place.

Combining this with static type checking (and maybe some unit tests) you can ensure that any message one microservice can send, the other can read as long as they use the same model to pack/unpack their JSONs.

Now you have a model that knows how to read data from the JSON (not the raw string, actually, but to the types that are allowed by the standard json.dumps function e.g. dict, list, str, int, float, bool, None ) ...

Leave a Comment
Related Posts