-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathviews.py
More file actions
1663 lines (1406 loc) · 60.1 KB
/
Copy pathviews.py
File metadata and controls
1663 lines (1406 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import os
import random
import string
from importlib.metadata import version
from typing import Any, Optional
from data.models import Concept
from datasets.serializers import DataPartnerSerializer
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from jobs.models import Job, JobStage, StageStatus
from mapping.models import (
DataDictionary,
DataPartner,
MappingRule,
OmopField,
ScanReport,
ScanReportConcept,
ScanReportField,
ScanReportTable,
ScanReportValue,
)
from mapping.permissions import get_user_permissions_on_scan_report
from rest_framework import status, viewsets
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import (
CreateModelMixin,
DestroyModelMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
)
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from services.rules import (
_find_destination_table,
save_mapping_rules,
)
from services.rules_export import (
get_mapping_rules_json,
get_mapping_rules_list,
make_dag,
)
from services.storage_service import StorageService
from services.worker_service import get_worker_service
from api.filters import (
ScanReportAccessFilter,
ScanReportFieldFilter,
ScanReportValueFilter,
)
from api.mixins import ScanReportPermissionMixin
from api.paginations import CustomPagination
from api.serializers import (
ConceptSerializerV2,
GetRulesAnalysis,
ScanReportConceptDetailSerializerV3,
ScanReportConceptSerializer,
ScanReportCreateSerializer,
ScanReportEditSerializer,
ScanReportFieldEditSerializer,
ScanReportFieldListSerializerV2,
ScanReportFieldListSerializerV3,
ScanReportFilesSerializer,
ScanReportTableEditSerializer,
ScanReportTableListSerializerV2,
ScanReportValueViewSerializerV2,
ScanReportValueViewSerializerV3,
ScanReportViewSerializerV2,
UserSerializer,
)
storage_service = StorageService()
worker_service = get_worker_service()
class DataPartnerViewSet(GenericAPIView, ListModelMixin):
"""
A viewset for handling DataPartner objects.
This viewset provides a GET method to retrieve a list of all
DataPartner objects using the ListModelMixin.
Attributes:
queryset (QuerySet): A queryset containing all DataPartner objects.
serializer_class (Serializer): The serializer class used for
serializing and deserializing DataPartner objects.
Methods:
get(request, *args, **kwargs):
Handles GET requests to return a list of DataPartner objects.
"""
queryset = DataPartner.objects.all().order_by("name")
serializer_class = DataPartnerSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class ConceptFilterViewSetV2(GenericAPIView, ListModelMixin):
"""
A viewset for filtering and listing Concept objects.
This viewset provides functionality to filter and paginate Concept
objects based on specified fields and their values. It uses
DjangoFilterBackend for filtering and a custom pagination class for
paginating the results.
Attributes:
queryset (QuerySet): The base queryset for retrieving Concept
objects, ordered by `concept_id`.
serializer_class (Serializer): The serializer class used for
serializing Concept objects.
filter_backends (list): A list of filter backends to apply to
the queryset.
pagination_class (Pagination): The pagination class used for
paginating the results.
filterset_fields (dict): A dictionary defining the fields that
can be filtered and the types of filtering allowed for each
field.
Methods:
get(request, *args, **kwargs):
Handles GET requests to retrieve a filtered and paginated
list of Concept objects.
"""
queryset = Concept.objects.all().order_by("concept_id")
serializer_class = ConceptSerializerV2
filter_backends = [DjangoFilterBackend]
pagination_class = CustomPagination
filterset_fields = {
"concept_id": ["in", "exact"],
"concept_code": ["in", "exact"],
"vocabulary_id": ["in", "exact"],
}
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class UserViewSet(GenericAPIView, ListModelMixin):
"""
A viewset for handling user-related API requests.
This viewset provides a GET method to retrieve a list of users.
Attributes:
queryset (QuerySet): The queryset containing all User objects.
serializer_class (Serializer): The serializer class used to
serialize User objects.
Methods:
get(request, *args, **kwargs):
Handles GET requests to return a list of users.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class UserFilterViewSet(GenericAPIView, ListModelMixin):
"""
A viewset for filtering and listing User objects.
Supports filtering by `id` (exact, in) and `is_active` (exact).
Methods:
get(request, *args, **kwargs): Returns a filtered list of users.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["id", "username"]
filterset_fields = {"id": ["in", "exact"], "is_active": ["exact"]}
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class UserDetailView(APIView):
"""
A view that handles retrieving the details of the authenticated user.
This view requires the user to be authenticated and uses the
`IsAuthenticated` permission class to enforce this. When a GET
request is made to this view, it serializes the authenticated
user's data using the `UserSerializer` and returns it in the
response.
Methods:
get(request, *args, **kwargs):
Handles GET requests. Serializes the authenticated user's
data and returns it in the response.
Attributes:
permission_classes (list): A list of permission classes that
restrict access to authenticated users only.
"""
permission_classes = [IsAuthenticated]
@extend_schema(
request=OpenApiTypes.OBJECT,
responses={
200: OpenApiTypes.OBJECT,
401: OpenApiTypes.OBJECT,
},
description="Retrieve the details of the authenticated user.",
)
def get(self, request, *args, **kwargs):
serializer = UserSerializer(request.user)
return Response(serializer.data)
class ScanReportIndexV2(GenericAPIView, ListModelMixin, CreateModelMixin):
"""
A custom viewset for managing and listing scan reports with
enhanced functionality for version 2.
This viewset extends the base functionality to include:
- Advanced filtering options for scan reports based on various fields.
- Custom ordering capabilities to sort scan reports by specific
attributes.
- Integration with a custom pagination class for efficient data
retrieval.
Features:
- Supports filtering by fields such as `hidden`, `dataset`,
`upload_status`, and more.
- Allows ordering by attributes like `id`, `name`, `created_at`, and
`dataset`.
- Provides a seamless interface for retrieving and creating scan
reports.
Methods:
- `get`: Handles GET requests to retrieve a paginated and filtered
list of scan reports.
- `post`: Handles POST requests to create new scan reports with file
uploads.
"""
queryset = ScanReport.objects.all()
parser_classes = [MultiPartParser, FormParser]
filter_backends = [
DjangoFilterBackend,
OrderingFilter,
ScanReportAccessFilter,
]
filterset_fields = {
"hidden": ["exact"],
"dataset": ["in", "icontains"],
"upload_status__value": ["in"],
"mapping_status__value": ["in"],
"parent_dataset": ["exact"],
}
ordering_fields = [
"id",
"name",
"created_at",
"dataset",
"parent_dataset",
]
pagination_class = CustomPagination
ordering = "-created_at"
@extend_schema(responses=ScanReportViewSerializerV2)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_scan_report_file(self, request):
return request.data.get("scan_report_file", None)
def get_serializer_class(self):
if self.request.method in ["GET"]:
return ScanReportViewSerializerV2
if self.request.method in ["POST"]:
return ScanReportFilesSerializer
if self.request.method in ["DELETE", "PATCH", "PUT"]:
return ScanReportEditSerializer
return super().get_serializer_class()
def post(self, request, *args, **kwargs):
non_file_serializer = ScanReportCreateSerializer(
data=request.data, context={"request": request}
)
if not non_file_serializer.is_valid():
return Response(
non_file_serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
file_serializer = self.get_serializer(data=request.FILES)
if not file_serializer.is_valid():
return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(file_serializer, non_file_serializer)
headers = self.get_success_headers(file_serializer.data)
return Response(
file_serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
def perform_create(self, serializer, non_file_serializer):
validatedFiles = serializer.validated_data
validatedData = non_file_serializer.validated_data
# List all the validated data and files
valid_data_dictionary_file = validatedFiles.get("data_dictionary_file")
valid_scan_report_file = validatedFiles.get("scan_report_file")
valid_visibility = validatedData.get("visibility")
valid_viewers = validatedData.get("viewers")
valid_editors = validatedData.get("editors")
valid_dataset = validatedData.get("dataset")
valid_parent_dataset = validatedData.get("parent_dataset")
rand = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
dt = "{:%Y%m%d-%H%M%S}".format(datetime.datetime.now())
# Create an entry in ScanReport for the uploaded Scan Report
scan_report = ScanReport.objects.create(
dataset=valid_dataset,
parent_dataset=valid_parent_dataset,
name=storage_service.modify_filename(valid_scan_report_file, dt, rand),
visibility=valid_visibility,
)
scan_report.author = self.request.user
scan_report.save()
# Add viewers to the scan report if specified
if sr_viewers := valid_viewers:
scan_report.viewers.add(*sr_viewers)
# Add editors to the scan report if specified
if sr_editors := valid_editors:
scan_report.editors.add(*sr_editors)
# Spreadsheet Content Type
spreadsheet_content_type = (
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# If there's no data dictionary supplied, only upload the scan report
# Set data_dictionary_blob in Azure message to None
if str(valid_data_dictionary_file) == "None":
message_body = {
"scan_report_id": scan_report.id,
"scan_report_blob": scan_report.name,
"data_dictionary_blob": "None",
}
storage_service.upload_file(
scan_report.name,
"scan-reports",
valid_scan_report_file,
spreadsheet_content_type,
use_read_method=False,
)
else:
data_dictionary = DataDictionary.objects.create(
name=f"{os.path.splitext(str(valid_data_dictionary_file))[0]}"
f"_{dt}{rand}.csv"
)
data_dictionary.save()
scan_report.data_dictionary = data_dictionary
scan_report.save()
message_body = {
"scan_report_id": scan_report.id,
"scan_report_blob": scan_report.name,
"data_dictionary_blob": data_dictionary.name,
}
storage_service.upload_file(
scan_report.name,
"scan-reports",
valid_scan_report_file,
spreadsheet_content_type,
use_read_method=False,
)
storage_service.upload_file(
data_dictionary.name,
"data-dictionaries",
valid_data_dictionary_file,
"text/csv",
use_read_method=False,
)
# send to the workers service
worker_service.trigger_scan_report_processing(message_body)
class ScanReportDetailV2(
ScanReportPermissionMixin,
GenericAPIView,
RetrieveModelMixin,
UpdateModelMixin,
DestroyModelMixin,
):
"""
A view for handling detailed operations on ScanReport objects.
This class-based view provides functionality for retrieving,
updating, and deleting ScanReport objects. It uses different
serializers based on the HTTP method of the request.
Inherits:
- ScanReportPermissionMixin: Mixin to handle permissions for
ScanReport objects.
- GenericAPIView: Base class for generic API views.
- RetrieveModelMixin: Mixin to add retrieve functionality.
- UpdateModelMixin: Mixin to add update functionality.
- DestroyModelMixin: Mixin to add delete functionality.
Attributes:
queryset (QuerySet): The queryset of ScanReport objects.
serializer_class (Serializer): The default serializer class for
the view.
Methods:
get_serializer_class():
Returns the appropriate serializer class based on the HTTP
method.
get(request, *args, **kwargs):
Handles GET requests to retrieve a ScanReport object.
patch(request, *args, **kwargs):
Handles PATCH requests to partially update a ScanReport
object.
delete(request, *args, **kwargs):
Handles DELETE requests to delete a ScanReport object.
perform_destroy(instance):
Deletes the given ScanReport instance and its associated
data from the storage service.
"""
queryset = ScanReport.objects.all()
serializer_class = ScanReportViewSerializerV2
def get_serializer_class(self):
if self.request.method in ["GET"]:
return ScanReportViewSerializerV2
if self.request.method in ["POST"]:
return ScanReportFilesSerializer
if self.request.method in ["DELETE", "PATCH", "PUT"]:
return ScanReportEditSerializer
return super().get_serializer_class()
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
def perform_destroy(self, instance):
try:
storage_service.delete_file(instance.name, "scan-reports")
except Exception as e:
raise Exception(f"Error deleting scan report: {e}")
if instance.data_dictionary:
try:
storage_service.delete_file(
instance.data_dictionary.name, "data-dictionaries"
)
except Exception as e:
raise Exception(f"Error deleting data dictionary: {e}")
instance.delete()
class ScanReportTableIndexV2(ScanReportPermissionMixin, GenericAPIView, ListModelMixin):
"""
ScanReportTableIndexV2 is a view that provides a paginated list of
Scan Report Tables associated with a specific Scan Report. It
supports filtering, ordering, and pagination.
Features:
- **Filtering**: Allows filtering by the `name` field using
case-insensitive containment (`icontains`).
- **Ordering**: Supports ordering by `name`, `person_id`, and
`date_event`. Default ordering is by `-created_at`.
- **Pagination**: Utilizes a custom pagination class
(`CustomPagination`) for paginated responses.
Attributes:
- `filterset_fields`: Defines the fields available for filtering.
- `filter_backends`: Specifies the backends used for filtering and
ordering.
- `ordering_fields`: Lists the fields available for ordering.
- `pagination_class`: Specifies the pagination class to be used.
- `ordering`: Defines the default ordering for the queryset.
- `serializer_class`: Specifies the serializer used for serializing
the response data.
Methods:
- `get`: Handles GET requests and returns a paginated list of Scan
Report Tables.
- `get_queryset`: Returns the queryset of Scan Report Tables
filtered by the associated Scan Report.
"""
filterset_fields = {
"name": ["icontains"],
}
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["name", "person_id", "date_event"]
pagination_class = CustomPagination
ordering = "-created_at"
serializer_class = ScanReportTableListSerializerV2
@extend_schema(responses=ScanReportTableListSerializerV2)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return ScanReportTable.objects.filter(scan_report=self.scan_report)
class ScanReportTableDetailV2(
ScanReportPermissionMixin, GenericAPIView, RetrieveModelMixin, UpdateModelMixin
):
"""
A view for handling detailed operations on ScanReportTable objects.
This view provides functionality for retrieving and updating
ScanReportTable instances. It uses different serializers for GET and
modification requests (PUT, PATCH, DELETE). Additionally, it triggers
background jobs for mapping rules when a partial update (PATCH) is
performed.
Attributes:
queryset (QuerySet): The queryset of ScanReportTable objects.
serializer_class (Serializer): The default serializer class for
the view.
Methods:
get_object():
Retrieves a ScanReportTable instance based on the provided
table_pk.
get(request, *args, **kwargs):
Handles GET requests to retrieve a ScanReportTable instance.
get_serializer_class():
Determines the serializer class to use based on the request
method.
patch(request, *args, **kwargs):
Handles PATCH requests to partially update a ScanReportTable
instance. Deletes existing mapping rules, triggers
background jobs for mapping, and ensures no duplicate jobs
are running for the same table.
"""
queryset = ScanReportTable.objects.all()
serializer_class = ScanReportTableListSerializerV2
def get_object(self):
return get_object_or_404(self.queryset, pk=self.kwargs["table_pk"])
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def get_serializer_class(self):
if self.request.method in ["GET", "POST"]:
# use the view serialiser if on GET requests
return ScanReportTableListSerializerV2
if self.request.method in ["PUT", "PATCH", "DELETE"]:
# use the edit serialiser when the user tries to alter the scan report
return ScanReportTableEditSerializer
return super().get_serializer_class()
def patch(self, request: Any, *args: Any, **kwargs: Any) -> Response:
"""
Perform a partial update on the instance and trigger background
processing jobs.
This method handles the partial update of a database instance,
deletes existing mapping rules, and triggers a series of
background jobs to process the updated data. It ensures that no
duplicate jobs are created for the same table while a job is
already in progress.
Args:
request (Any): The HTTP request object containing the data for
the update.
**kwargs (Any): Additional keyword arguments. The "partial" key
is used to determine if the update is partial (default is
True).
Returns:
Response: A DRF Response object containing the serialized data
of the updated instance or an error message if a job is
already in progress.
Raises:
requests.exceptions.HTTPError: If the HTTP request to the worker
service fails.
Workflow:
1. Retrieve the instance to be updated.
2. Validate and apply the partial update using the serializer.
3. Delete existing mapping rules for the instance.
4. Prepare and send a message to the worker service to trigger
background jobs.
5. Create job records for the processing stages:
- BUILD_CONCEPTS_FROM_DICT (initial stage, marked as
IN_PROGRESS)
- REUSE_CONCEPTS
- GENERATE_RULES
6. Handle any HTTP errors during the worker service request.
Notes:
- The worker service URL and credentials are configured in the
application settings.
- If a job is already in progress for the table, the method
returns a 400 BAD REQUEST response with an appropriate error
message.
- The worker ID returned by the worker service is not currently
saved but can be utilized for tracking job status in the
future.
"""
instance: ScanReportTable = self.get_object()
partial = kwargs.pop("partial", True)
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
# Map the table
scan_report_instance: ScanReport = instance.scan_report
data_dictionary_name: Optional[str] = (
scan_report_instance.data_dictionary.name
if scan_report_instance.data_dictionary
else None
)
# Prevent double-updating from backend
if Job.objects.filter(
scan_report_table=instance,
status=StageStatus.objects.get(value="IN_PROGRESS"),
):
return Response(
{
"detail": "There is a job running for this table. Please wait until it complete before updating."
},
status=status.HTTP_400_BAD_REQUEST,
)
# Trigger auto mapping
worker_service.trigger_auto_mapping(
scan_report=scan_report_instance,
table=instance,
data_dictionary_name=data_dictionary_name,
trigger_reuse_concepts=instance.trigger_reuse,
)
# Create Job records if no errors
# For the first stage, default status is IN_PROGRESS
Job.objects.create(
scan_report=scan_report_instance,
scan_report_table=instance,
stage=JobStage.objects.get(value="BUILD_CONCEPTS_FROM_DICT"),
status=StageStatus.objects.get(value="IN_PROGRESS"),
)
for stage in [
"REUSE_CONCEPTS",
"GENERATE_RULES",
]:
Job.objects.create(
scan_report=scan_report_instance,
scan_report_table=instance,
stage=JobStage.objects.get(value=stage),
)
# TODO: The worker_id can be used for status, but we need to save it somewhere.
# resp_json = response.json()
# worker_id = resp_json.get("instanceId")
return Response(serializer.data)
class ScanReportFieldIndexV2(ScanReportPermissionMixin, GenericAPIView, ListModelMixin):
"""
A view that provides a list of ScanReportField objects associated
with a specific ScanReportTable. This view supports filtering,
ordering, and pagination for the ScanReportField objects. It also
caches the response for 15 minutes and varies the cache based on
cookies.
Attributes:
serializer_class (Serializer): The serializer class used for
serializing the ScanReportField objects.
filterset_fields (dict): Fields that can be filtered, with
their respective lookup expressions.
filter_backends (list): List of filter backends used for
filtering and ordering.
ordering_fields (list): Fields that can be used for ordering
the results.
pagination_class (Pagination): The pagination class used for
paginating the results.
Methods:
get(request, *args, **kwargs):
Handles GET requests and retrieves the ScanReportTable
object based on the provided table_pk. Returns a list of
ScanReportField objects associated with the table.
get_queryset():
Returns the queryset of ScanReportField objects filtered by
the associated ScanReportTable.
list(request, *args, **kwargs):
Overrides the default list method to add caching and
cookie-based variation. Returns the paginated and
serialized list of ScanReportField objects.
"""
serializer_class = ScanReportFieldListSerializerV2
filterset_fields = {
"name": ["icontains"],
}
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["name", "description_column", "type_column"]
pagination_class = CustomPagination
@extend_schema(responses=ScanReportFieldListSerializerV2)
def get(self, request, *args, **kwargs):
self.table = get_object_or_404(ScanReportTable, pk=kwargs["table_pk"])
return self.list(request, *args, **kwargs)
def get_queryset(self):
return ScanReportField.objects.filter(scan_report_table=self.table).order_by(
"id"
)
@method_decorator(cache_page(60 * 15))
@method_decorator(vary_on_cookie)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
class ScanReportFieldDetailV2(
ScanReportPermissionMixin, GenericAPIView, RetrieveModelMixin, UpdateModelMixin
):
"""
A view for handling detailed operations on ScanReportField objects.
This view supports retrieving and partially updating a
ScanReportField object. It uses different serializers for different
HTTP methods and ensures proper permissions are applied through the
ScanReportPermissionMixin.
Inherits:
- ScanReportPermissionMixin: Ensures the user has the required
permissions.
- GenericAPIView: Provides base functionality for API views.
- RetrieveModelMixin: Adds support for retrieving a single
model instance.
- UpdateModelMixin: Adds support for updating a model instance.
Attributes:
model (Model): The model class associated with this view
(ScanReportField).
serializer_class (Serializer): The default serializer class for
the view.
Methods:
get_object():
Retrieves the ScanReportField object based on the
`field_pk` URL parameter. Returns a 404 response if the
object is not found.
get(request, *args, **kwargs):
Handles GET requests to retrieve a ScanReportField object.
patch(request, *args, **kwargs):
Handles PATCH requests to partially update a
ScanReportField object.
get_serializer_class():
Determines the serializer class to use based on the HTTP
method.
- GET, POST: Uses ScanReportFieldListSerializerV2.
- PUT, PATCH: Uses ScanReportFieldEditSerializer.
Falls back to the default implementation for other methods.
"""
model = ScanReportField
serializer_class = ScanReportFieldListSerializerV2
def get_object(self):
return get_object_or_404(self.model, pk=self.kwargs["field_pk"])
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def get_serializer_class(self):
if self.request.method in ["GET", "POST"]:
return ScanReportFieldListSerializerV2
if self.request.method in ["PUT", "PATCH"]:
return ScanReportFieldEditSerializer
return super().get_serializer_class()
class ScanReportFieldIndexV3(ScanReportPermissionMixin, GenericAPIView, ListModelMixin):
"""
A view that provides a list of ScanReportField objects associated
with a specific ScanReportTable. Each field is returned with its
nested ``concepts`` and ``mapping_recommendations`` so the client
can render concept tags without follow-up requests. This view
supports filtering (including ``has_concepts`` and
``creation_type``), ordering, and pagination.
Attributes:
serializer_class (Serializer): The serializer class used for
serializing the ScanReportField objects (V3 — includes
nested concepts and mapping recommendations).
filterset_class (FilterSet): The filterset used for filtering,
including the ``has_concepts`` and ``creation_type``
filters.
filter_backends (list): List of filter backends used for
filtering and ordering.
ordering_fields (list): Fields that can be used for ordering
the results.
pagination_class (Pagination): The pagination class used for
paginating the results.
Methods:
get(request, *args, **kwargs):
Handles GET requests and retrieves the ScanReportTable
object based on the provided table_pk. Returns a list of
ScanReportField objects associated with the table.
get_queryset():
Returns the queryset of ScanReportField objects filtered by
the associated ScanReportTable, with ``select_related`` and
``prefetch_related`` applied to avoid N+1 queries when
serializing nested concepts and mapping recommendations.
list(request, *args, **kwargs):
Returns the paginated and serialized list of
ScanReportField objects. Caching is intentionally omitted
(unlike V2) so concept edits are reflected immediately.
"""
filterset_class = ScanReportFieldFilter
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["name", "description_column", "type_column"]
pagination_class = CustomPagination
serializer_class = ScanReportFieldListSerializerV3
@extend_schema(responses=ScanReportFieldListSerializerV3)
def get(self, request, *args, **kwargs):
self.table = get_object_or_404(ScanReportTable, pk=kwargs["table_pk"])
return self.list(request, *args, **kwargs)
def get_queryset(self):
return (
ScanReportField.objects.filter(scan_report_table=self.table)
.order_by("id")
.select_related("scan_report_table")
.prefetch_related(
"concepts",
"concepts__concept",
"mapping_recommendations",
"mapping_recommendations__concept",
)
)
class ScanReportValueListV2(ScanReportPermissionMixin, GenericAPIView, ListModelMixin):
"""
A view for listing ScanReportValue objects associated with a
specific ScanReportField. This view provides filtering,
pagination, and caching capabilities for the ScanReportValue
objects. It uses DjangoFilterBackend for filtering and a custom
pagination class for paginated responses. The view also caches the
list response for 15 minutes.
Attributes:
filterset_fields (dict): Specifies the fields and lookup types
available for filtering.
filter_backends (list): Specifies the filter backends to be
used.
pagination_class (class): Specifies the pagination class to be
used.
serializer_class (class): Specifies the serializer class to be
used for the response.
Methods:
get(request, *args, **kwargs):
Handles GET requests and retrieves the ScanReportField
object based on the provided field_pk. Returns the list of
ScanReportValue objects associated with the field.
get_queryset():
Returns the queryset of ScanReportValue objects filtered by
the associated ScanReportField. The queryset is ordered by
ID and only includes specific fields.
list(request, *args, **kwargs):
Overrides the default list method to add caching and
vary-on-cookie functionality. Returns the paginated list of
ScanReportValue objects.
"""
filterset_fields = {
"value": ["in", "icontains"],
}
filter_backends = [DjangoFilterBackend]
pagination_class = CustomPagination
serializer_class = ScanReportValueViewSerializerV2
@extend_schema(responses=ScanReportValueViewSerializerV2)
def get(self, request, *args, **kwargs):
self.field = get_object_or_404(ScanReportField, pk=kwargs["field_pk"])
return self.list(request, *args, **kwargs)
def get_queryset(self):
return ScanReportValue.objects.filter(scan_report_field=self.field).order_by(
"id"
)
@method_decorator(cache_page(60 * 15))
@method_decorator(vary_on_cookie)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
class ScanReportValueListV3(ScanReportPermissionMixin, GenericAPIView, ListModelMixin):
"""
A view for listing ScanReportValue objects associated with a
specific ScanReportField. This view provides filtering,
pagination, and caching capabilities for the ScanReportValue
objects. It uses DjangoFilterBackend for filtering and a custom
pagination class for paginated responses. The view also caches the
list response for 15 minutes.
Attributes:
filterset_fields (dict): Specifies the fields and lookup types
available for filtering.
filter_backends (list): Specifies the filter backends to be
used.
pagination_class (class): Specifies the pagination class to be
used.
serializer_class (class): Specifies the serializer class to be
used for the response.
Methods:
get(request, *args, **kwargs):
Handles GET requests and retrieves the ScanReportField
object based on the provided field_pk. Returns the list of
ScanReportValue objects associated with the field.
get_queryset():
Returns the queryset of ScanReportValue objects filtered by
the associated ScanReportField. The queryset is ordered by
ID and only includes specific fields.
list(request, *args, **kwargs):
Overrides the default list method to add caching and
vary-on-cookie functionality. Returns the paginated list of
ScanReportValue objects.
"""
filterset_class = ScanReportValueFilter
filter_backends = [DjangoFilterBackend, OrderingFilter]
ordering_fields = ["value", "frequency", "value_description"]
pagination_class = CustomPagination
serializer_class = ScanReportValueViewSerializerV3
@extend_schema(responses=ScanReportValueViewSerializerV3)
def get(self, request, *args, **kwargs):
self.field = get_object_or_404(ScanReportField, pk=kwargs["field_pk"])
return self.list(request, *args, **kwargs)