Serialize tree object as JSON to DataTables Simple Object column: DONE
Retrieve JSON tree back from DataTables, and serialize back to Tree object: ???
What I’ve tried and what’s not working:
Code Sample:
@anvil.server.callable
def tree_example():
# Create tree object
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Mark", "mark", parent="jane")
print('This is the tree going to the server')
tree.show()
# Stuff tree object into database as JSON object
me = get_current_user()
me['topic_hierarchy'] = tree.to_json(with_data=True)
# Get tree JSON object from database, and print out the JSON object
tree2 = me['topic_hierarchy']
json_tree = json.loads(tree2)
for key in json_tree:
value = json_tree[key]
print("The key and value are ({}) = ({})".format(key, value))
So I can retrieve the JSON object, and print it out… but I’m not really sure how to recreate a Tree object from it… feels close.
It doesn’t look like treelib provides any from_json functionality. You’d need to parse your simple object data and recreate the tree using tree.create_node.
I think you’d be better off looking at the simple object column that gets stored in the database, and working your way from there. The structure of the tree should be evident in the nodes (e.g. they’ve got to store the name of the node, the name of its parent, etc).
A SimpleObject is usually a dict/list of dict/lists. That is, it is defined recursively.
Recursive data structures often call for recursive functions to process them. Hence, a recursive function (or two) could pick it apart, filling out the Tree as it goes.
Looking at that library’s github page there are several requests for a from_json function dating back several years.
There is even a pull request that implements it.
It will be a basic template for multi user, multi client application, where each user can have multiple clients, each of which can point to user specific hierarchical data, and a custom component to take the headache out of the whole process.
My use case: A custom component that shows a hierarchy of checkboxes for topics, indicating if a customer of a user is subscribed to those topics.
Soon I’ll be posting a hierarchical topics app in the “Show and Tell”