spaceapi-server/spaceapi_server/template/__init__.py

43 lines
1.2 KiB
Python
Raw Normal View History

2019-11-25 02:48:12 +01:00
2021-05-30 17:52:25 +02:00
class PluginInvocation():
_plugins = {}
2019-11-25 02:48:12 +01:00
2021-05-30 17:52:25 +02:00
def __init__(self, name, data):
super().__init__()
if name not in self._plugins:
raise KeyError(f'No such plugin function: {name}')
self._name = name
self._data = data
2019-11-25 02:48:12 +01:00
2021-05-30 17:52:25 +02:00
def __call__(self):
return self._plugins[self._name](**self._data)
2019-11-25 02:48:12 +01:00
2021-05-30 17:52:25 +02:00
@classmethod
def register_plugin(cls, name, fn):
cls._plugins[name] = fn
2019-11-25 02:48:12 +01:00
2021-05-30 17:52:25 +02:00
def plugin_constructor(loader, node):
data = loader.construct_mapping(node)
return PluginInvocation(node.tag[1:], data)
2019-11-25 04:35:50 +01:00
def render_traverse(obj):
"""
2021-05-30 17:52:25 +02:00
Walk through a complex, JSON-serializable data structure, and
invoke plugins if for custom tags.
2019-11-25 04:35:50 +01:00
:param obj: The object to traverse.
"""
if isinstance(obj, list):
# list -> recurse into each item
return [render_traverse(x) for x in obj]
2019-11-25 04:35:50 +01:00
elif isinstance(obj, dict):
# dict -> recurse into the value of each (key, value)
return {k: render_traverse(v) for k, v in obj.items()}
2021-05-30 17:52:25 +02:00
elif isinstance(obj, PluginInvocation):
# PluginTag -> invoke the plugin with the stored arguments
return obj()
2019-11-25 04:35:50 +01:00
else:
# anything else -> return as-is
return obj