Could we have a method (to_json
, perhaps?) to serialise instances of Portable Classes for use in http endpoints?
The Portable Classes machinery does a lot more than JSON serialisation. A __serialize__
method can return Media, datetime
objects, and even other Portable Classes (not to mention the global_data
parameter) – and, of course, there’s also a bunch of metadata to instruct the other end on how to reconstruct (which is an internal Anvil protocol subject to change). So, just because a class is portable doesn’t mean there’s a reliable way of turning it to/from JSON!
What semantics would you want from such a system?
Hi Owen - I’m not fully up to speed on the capabilities of Portable Classes although they looked brilliant when I played with them a couple of months ago.
Depending on your answer to Meredydd’s question about semantics, you might find what you need in CleverDict
, a package I’ve been working on which is about to release a major update.
It’s already on the install list for Anvil for server-side use. If you’d like a preview, you can install it locally from Test PyPI, or just search the README for ‘json’.
pip install -i https://test.pypi.org/simple/ cleverdict==1.8.0rc5
All the best,
Peter
OK. This was probably an unreasonable request!
I think I’ll stick to using marshmallow to define serialisation schema. It’s designed to so precisely that job and does it well.
If you are defining a JSON serialisation method, you can choose to use that as your __serialize__
implementation! You could do:
def __serialize__(self, global_data):
return self.serialize_to_json()
def __deserialize__(self, data, global_data):
return self.deserialize_from_json(data)
or, if your JSON serialization library wants to do all of the object construction:
@staticmethod
def __new_deserialized__(data, global_data):
return json_library.deserialize(type=my_class, json=data)
The Portable Classes system is a superset of JSON serialisation.