From 905bcd5965a715b19248a73389e0fca7e028a402 Mon Sep 17 00:00:00 2001 From: Rob van der Linde Date: Sat, 16 Mar 2024 23:46:40 +1300 Subject: [PATCH] views: traversal views don't show infinite nested data the flatten function will likely get moved after closes #43 --- src/sambal/views/domain.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/sambal/views/domain.py b/src/sambal/views/domain.py index d11ee6e..150a040 100644 --- a/src/sambal/views/domain.py +++ b/src/sambal/views/domain.py @@ -1,6 +1,19 @@ from pyramid.view import view_config -from sambal.resources import Resource, RootFactory +from sambal.resources import ContainerResource, Resource, RootFactory + + +def flatten(resource: Resource) -> dict: + """Remove nested containers at the view level. + + This can't easily be done at the Resource level otherwise it stops + traversal completely. + """ + # Filter children of containers to stop it returning infinite nested data. + if isinstance(resource, ContainerResource): + return {k: obj for k, obj in resource.items() if not isinstance(obj, Resource)} + + return resource @view_config(context=Resource, permission="read", renderer="json") @@ -11,4 +24,4 @@ def resource_view(context, request): For this to work a custom JSON encoder is used to deal with the various objects that aren't JSON encode-able out of the box. """ - return context + return {k: flatten(obj) for k, obj in context.items() if isinstance(obj, Resource)}