Coverage for backend/django/core/viewset.py: 92%
28 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-05-13 02:47 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-05-13 02:47 +0000
1from rest_framework import viewsets
4class ContextMixin:
5 """
6 A mixin that provides the flowsheet context to all views to enforce access control.
7 """
8 def initial(self, request, *args, **kwargs):
9 if hasattr(self, 'action'): 9 ↛ 14line 9 didn't jump to line 14 because the condition on line 9 was always true
10 view_method = getattr(self, self.action, None)
11 if hasattr(view_method, 'ignore_access_control') and view_method.ignore_access_control:
12 return super().initial(request, *args, **kwargs)
14 if hasattr(request, "query_params"): 14 ↛ 17line 14 didn't jump to line 17 because the condition on line 14 was always true
15 flowsheet_id = request.query_params.get("flowsheet")
16 else:
17 flowsheet_id = request.GET.get("flowsheet")
19 from core.validation import sanitize_flowsheet_id, flowsheet_context
21 flowsheet_id = sanitize_flowsheet_id(flowsheet_id)
22 write_intent = getattr(self, "action", None) in {"create", "update", "partial_update", "destroy"}
23 self.flowsheet_context = flowsheet_context(flowsheet_id, request.user, write_intent=write_intent)
24 # start the context
25 self.flowsheet_token = self.flowsheet_context.__enter__()
27 return super().initial(request, *args, **kwargs)
29 def finalize_response(self, request, response, *args, **kwargs):
30 # Clean up context when the response is finalized
31 if hasattr(self, 'flowsheet_context'):
32 self.flowsheet_context.__exit__(None, None, None)
34 return super().finalize_response(request, response, *args, **kwargs)
36 def handle_exception(self, exc):
37 # Clean up context in case of exception
38 if hasattr(self, 'flowsheet_context'):
39 self.flowsheet_context.__exit__(type(exc), exc, exc.__traceback__)
41 return super().handle_exception(exc)
43class ReadOnlyModelViewSet(ContextMixin, viewsets.ReadOnlyModelViewSet):
44 """
45 Use this model viewset for read-only operations instead of the default one to enforce access control.
46 """
47 pass
49class ModelViewSet(ContextMixin, viewsets.ModelViewSet):
50 """
51 Use this model viewset instead of the default one to enforce access control.
52 """
53 pass