views.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from collections import OrderedDict
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.db.models import Count
  4. from django.http import Http404
  5. from rest_framework import status
  6. from rest_framework.decorators import action
  7. from rest_framework.exceptions import PermissionDenied
  8. from rest_framework.response import Response
  9. from rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet
  10. from extras import filters
  11. from extras.models import (
  12. ConfigContext, CustomFieldChoice, ExportTemplate, Graph, ImageAttachment, ObjectChange, ReportResult, Tag,
  13. )
  14. from extras.reports import get_report, get_reports
  15. from extras.scripts import get_script, get_scripts
  16. from utilities.api import FieldChoicesViewSet, IsAuthenticatedOrLoginNotRequired, ModelViewSet
  17. from . import serializers
  18. #
  19. # Field choices
  20. #
  21. class ExtrasFieldChoicesViewSet(FieldChoicesViewSet):
  22. fields = (
  23. (ExportTemplate, ['template_language']),
  24. (Graph, ['type']),
  25. (ObjectChange, ['action']),
  26. )
  27. #
  28. # Custom field choices
  29. #
  30. class CustomFieldChoicesViewSet(ViewSet):
  31. """
  32. """
  33. permission_classes = [IsAuthenticatedOrLoginNotRequired]
  34. def __init__(self, *args, **kwargs):
  35. super(CustomFieldChoicesViewSet, self).__init__(*args, **kwargs)
  36. self._fields = OrderedDict()
  37. for cfc in CustomFieldChoice.objects.all():
  38. self._fields.setdefault(cfc.field.name, {})
  39. self._fields[cfc.field.name][cfc.value] = cfc.pk
  40. def list(self, request):
  41. return Response(self._fields)
  42. def retrieve(self, request, pk):
  43. if pk not in self._fields:
  44. raise Http404
  45. return Response(self._fields[pk])
  46. def get_view_name(self):
  47. return "Custom Field choices"
  48. #
  49. # Custom fields
  50. #
  51. class CustomFieldModelViewSet(ModelViewSet):
  52. """
  53. Include the applicable set of CustomFields in the ModelViewSet context.
  54. """
  55. def get_serializer_context(self):
  56. # Gather all custom fields for the model
  57. content_type = ContentType.objects.get_for_model(self.queryset.model)
  58. custom_fields = content_type.custom_fields.prefetch_related('choices')
  59. # Cache all relevant CustomFieldChoices. This saves us from having to do a lookup per select field per object.
  60. custom_field_choices = {}
  61. for field in custom_fields:
  62. for cfc in field.choices.all():
  63. custom_field_choices[cfc.id] = cfc.value
  64. custom_field_choices = custom_field_choices
  65. context = super().get_serializer_context()
  66. context.update({
  67. 'custom_fields': custom_fields,
  68. 'custom_field_choices': custom_field_choices,
  69. })
  70. return context
  71. def get_queryset(self):
  72. # Prefetch custom field values
  73. return super().get_queryset().prefetch_related('custom_field_values__field')
  74. #
  75. # Graphs
  76. #
  77. class GraphViewSet(ModelViewSet):
  78. queryset = Graph.objects.all()
  79. serializer_class = serializers.GraphSerializer
  80. filterset_class = filters.GraphFilter
  81. #
  82. # Export templates
  83. #
  84. class ExportTemplateViewSet(ModelViewSet):
  85. queryset = ExportTemplate.objects.all()
  86. serializer_class = serializers.ExportTemplateSerializer
  87. filterset_class = filters.ExportTemplateFilter
  88. #
  89. # Tags
  90. #
  91. class TagViewSet(ModelViewSet):
  92. queryset = Tag.objects.annotate(
  93. tagged_items=Count('extras_taggeditem_items', distinct=True)
  94. )
  95. serializer_class = serializers.TagSerializer
  96. filterset_class = filters.TagFilter
  97. #
  98. # Image attachments
  99. #
  100. class ImageAttachmentViewSet(ModelViewSet):
  101. queryset = ImageAttachment.objects.all()
  102. serializer_class = serializers.ImageAttachmentSerializer
  103. #
  104. # Config contexts
  105. #
  106. class ConfigContextViewSet(ModelViewSet):
  107. queryset = ConfigContext.objects.prefetch_related(
  108. 'regions', 'sites', 'roles', 'platforms', 'tenant_groups', 'tenants',
  109. )
  110. serializer_class = serializers.ConfigContextSerializer
  111. filterset_class = filters.ConfigContextFilter
  112. #
  113. # Reports
  114. #
  115. class ReportViewSet(ViewSet):
  116. permission_classes = [IsAuthenticatedOrLoginNotRequired]
  117. _ignore_model_permissions = True
  118. exclude_from_schema = True
  119. lookup_value_regex = '[^/]+' # Allow dots
  120. def _retrieve_report(self, pk):
  121. # Read the PK as "<module>.<report>"
  122. if '.' not in pk:
  123. raise Http404
  124. module_name, report_name = pk.split('.', 1)
  125. # Raise a 404 on an invalid Report module/name
  126. report = get_report(module_name, report_name)
  127. if report is None:
  128. raise Http404
  129. return report
  130. def list(self, request):
  131. """
  132. Compile all reports and their related results (if any). Result data is deferred in the list view.
  133. """
  134. report_list = []
  135. # Iterate through all available Reports.
  136. for module_name, reports in get_reports():
  137. for report in reports:
  138. # Attach the relevant ReportResult (if any) to each Report.
  139. report.result = ReportResult.objects.filter(report=report.full_name).defer('data').first()
  140. report_list.append(report)
  141. serializer = serializers.ReportSerializer(report_list, many=True, context={
  142. 'request': request,
  143. })
  144. return Response(serializer.data)
  145. def retrieve(self, request, pk):
  146. """
  147. Retrieve a single Report identified as "<module>.<report>".
  148. """
  149. # Retrieve the Report and ReportResult, if any.
  150. report = self._retrieve_report(pk)
  151. report.result = ReportResult.objects.filter(report=report.full_name).first()
  152. serializer = serializers.ReportDetailSerializer(report)
  153. return Response(serializer.data)
  154. @action(detail=True, methods=['post'])
  155. def run(self, request, pk):
  156. """
  157. Run a Report and create a new ReportResult, overwriting any previous result for the Report.
  158. """
  159. # Check that the user has permission to run reports.
  160. if not request.user.has_perm('extras.add_reportresult'):
  161. raise PermissionDenied("This user does not have permission to run reports.")
  162. # Retrieve and run the Report. This will create a new ReportResult.
  163. report = self._retrieve_report(pk)
  164. report.run()
  165. serializer = serializers.ReportDetailSerializer(report)
  166. return Response(serializer.data)
  167. #
  168. # Scripts
  169. #
  170. class ScriptViewSet(ViewSet):
  171. permission_classes = [IsAuthenticatedOrLoginNotRequired]
  172. _ignore_model_permissions = True
  173. exclude_from_schema = True
  174. lookup_value_regex = '[^/]+' # Allow dots
  175. def _get_script(self, pk):
  176. module_name, script_name = pk.split('.')
  177. script = get_script(module_name, script_name)
  178. if script is None:
  179. raise Http404
  180. return script
  181. def list(self, request):
  182. flat_list = []
  183. for script_list in get_scripts().values():
  184. flat_list.extend(script_list.values())
  185. serializer = serializers.ScriptSerializer(flat_list, many=True, context={'request': request})
  186. return Response(serializer.data)
  187. def retrieve(self, request, pk):
  188. script = self._get_script(pk)
  189. serializer = serializers.ScriptSerializer(script, context={'request': request})
  190. return Response(serializer.data)
  191. def post(self, request, pk):
  192. """
  193. Run a Script identified as "<module>.<script>".
  194. """
  195. script = self._get_script(pk)()
  196. input_serializer = serializers.ScriptInputSerializer(data=request.data)
  197. if input_serializer.is_valid():
  198. output = script.run(input_serializer.data['data'])
  199. script.output = output
  200. output_serializer = serializers.ScriptOutputSerializer(script)
  201. return Response(output_serializer.data)
  202. return Response(input_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  203. #
  204. # Change logging
  205. #
  206. class ObjectChangeViewSet(ReadOnlyModelViewSet):
  207. """
  208. Retrieve a list of recent changes.
  209. """
  210. queryset = ObjectChange.objects.prefetch_related('user')
  211. serializer_class = serializers.ObjectChangeSerializer
  212. filterset_class = filters.ObjectChangeFilter