-
Notifications
You must be signed in to change notification settings - Fork 30
/
views.py
428 lines (331 loc) · 16.5 KB
/
views.py
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
import logging
from celery_once import AlreadyQueued
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.http import Http404
from django.shortcuts import get_object_or_404
from drf_yasg.utils import swagger_auto_schema
from pydash import get
from rest_framework import status, mixins
from rest_framework.generics import (
RetrieveAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, UpdateAPIView
)
from rest_framework.response import Response
from core.client_configs.views import ResourceClientConfigsView
from core.common.constants import HEAD, RELEASED_PARAM, PROCESSING_PARAM, NOT_FOUND, MUST_SPECIFY_EXTRA_PARAM_IN_BODY
from core.common.mixins import ListWithHeadersMixin, ConceptDictionaryCreateMixin, ConceptDictionaryUpdateMixin, \
ConceptContainerExportMixin, ConceptContainerProcessingMixin
from core.common.permissions import CanViewConceptDictionary, CanEditConceptDictionary, HasAccessToVersionedObject, \
CanViewConceptDictionaryVersion
from core.common.swagger_parameters import q_param, limit_param, sort_desc_param, sort_asc_param, exact_match_param, \
page_param, verbose_param, include_retired_param, updated_since_param, include_facets_header, compress_header
from core.common.tasks import export_source
from core.common.utils import parse_boolean_query_param, compact_dict_by_values
from core.common.views import BaseAPIView, BaseLogoView
from core.sources.constants import DELETE_FAILURE, DELETE_SUCCESS, VERSION_ALREADY_EXISTS
from core.sources.documents import SourceDocument
from core.sources.models import Source
from core.sources.search import SourceSearch
from core.sources.serializers import (
SourceDetailSerializer, SourceListSerializer, SourceCreateSerializer, SourceVersionDetailSerializer,
SourceVersionListSerializer, SourceVersionExportSerializer, SourceSummaryDetailSerializer,
SourceVersionSummaryDetailSerializer)
logger = logging.getLogger('oclapi')
class SourceBaseView(BaseAPIView):
lookup_field = 'source'
pk_field = 'mnemonic'
model = Source
permission_classes = (CanViewConceptDictionary,)
queryset = Source.objects.filter(is_active=True)
@staticmethod
def get_detail_serializer(obj):
return SourceDetailSerializer(obj)
def get_filter_params(self, default_version_to_head=True):
query_params = self.request.query_params.dict()
version = query_params.get('version', None) or self.kwargs.get('version', None)
if not version and default_version_to_head:
version = HEAD
kwargs = self.kwargs.copy()
if self.user_is_self and self.request.user.is_authenticated:
kwargs['user'] = self.request.user.username
return {**query_params.copy(), **kwargs, 'version': version}
def get_queryset(self):
queryset = Source.get_base_queryset(
compact_dict_by_values(self.get_filter_params())
).select_related(
'user', 'organization'
)
if self.is_verbose():
queryset = queryset.select_related('created_by', 'updated_by')
return queryset
class SourceVersionBaseView(SourceBaseView):
def get_filter_params(self, default_version_to_head=False):
return super().get_filter_params(default_version_to_head)
class SourceListView(SourceBaseView, ConceptDictionaryCreateMixin, ListWithHeadersMixin):
serializer_class = SourceListSerializer
is_searchable = True
es_fields = Source.es_fields
document_model = SourceDocument
facet_class = SourceSearch
default_filters = dict(is_active=True, version=HEAD)
def get_serializer_class(self):
if self.request.method == 'GET' and self.is_verbose():
return SourceDetailSerializer
if self.request.method == 'POST':
return SourceCreateSerializer
return SourceListSerializer
@swagger_auto_schema(
manual_parameters=[
q_param, limit_param, sort_desc_param, sort_asc_param, exact_match_param, page_param, verbose_param,
include_retired_param, updated_since_param, include_facets_header, compress_header
]
)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_csv_rows(self, queryset=None): # pragma: no cover
if not queryset:
queryset = self.get_queryset()
values = queryset.values('mnemonic', 'name', 'full_name', 'source_type', 'description', 'default_locale',
'supported_locales', 'website', 'external_id', 'updated_at', 'updated_by', 'uri')
for value in values:
value['Owner'] = Source.objects.get(uri=value['uri']).parent.mnemonic
value['Source ID'] = value.pop('mnemonic')
value['Source Name'] = value.pop('name')
value['Source Full Name'] = value.pop('full_name')
value['Source Type'] = value.pop('source_type')
value['Description'] = value.pop('description')
value['Default Locale'] = value.pop('default_locale')
value['Supported Locales'] = ",".join(value.pop('supported_locales'))
value['Website'] = value.pop('website')
value['External ID'] = value.pop('external_id')
value['Last Updated'] = value.pop('updated_at')
value['Updated By'] = value.pop('updated_by')
value['URI'] = value.pop('uri')
values.field_names.extend([
'Owner', 'Source ID', 'Source Name', 'Source Full Name', 'Source Type', 'Description', 'Default Locale',
'Supported Locales', 'Website', 'External ID', 'Last Updated', 'Updated By', 'URI'
])
del values.field_names[0:12]
return values
class SourceLogoView(SourceBaseView, BaseLogoView):
serializer_class = SourceDetailSerializer
def get_permissions(self):
if self.request.method in ['GET', 'HEAD']:
return [CanViewConceptDictionary()]
return [CanEditConceptDictionary()]
class SourceRetrieveUpdateDestroyView(SourceBaseView, ConceptDictionaryUpdateMixin, RetrieveAPIView):
serializer_class = SourceDetailSerializer
def get_object(self, queryset=None):
instance = self.get_queryset().filter(is_active=True).order_by('-created_at').first()
if not instance:
raise Http404()
self.check_object_permissions(self.request, instance)
return instance
def get_permissions(self):
if self.request.method in ['GET', 'HEAD']:
return [CanViewConceptDictionary()]
return [CanEditConceptDictionary()]
def delete(self, request, *args, **kwargs): # pylint: disable=unused-argument
source = self.get_object()
try:
source.delete()
except Exception as ex:
return Response({'detail': get(ex, 'messages', [DELETE_FAILURE])}, status=status.HTTP_400_BAD_REQUEST)
return Response({'detail': DELETE_SUCCESS}, status=status.HTTP_204_NO_CONTENT)
class SourceVersionListView(SourceVersionBaseView, mixins.CreateModelMixin, ListWithHeadersMixin):
released_filter = None
processing_filter = None
default_qs_sort_attr = '-created_at'
def get_serializer_class(self):
if self.request.method in ['GET', 'HEAD'] and self.is_verbose():
return SourceVersionDetailSerializer
if self.request.method == 'POST':
return SourceCreateSerializer
return SourceVersionListSerializer
def get(self, request, *args, **kwargs):
self.released_filter = parse_boolean_query_param(request, RELEASED_PARAM, self.released_filter)
self.processing_filter = parse_boolean_query_param(request, PROCESSING_PARAM, self.processing_filter)
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
head_object = self.get_queryset().first()
version = request.data.pop('id', None)
payload = {
"mnemonic": head_object.mnemonic, "id": head_object.mnemonic, "name": head_object.name, **request.data,
"organization_id": head_object.organization_id, "user_id": head_object.user_id,
'version': version
}
serializer = self.get_serializer(data=payload)
if serializer.is_valid():
try:
instance = serializer.create_version(payload)
if serializer.is_valid():
serializer = SourceDetailSerializer(instance, context={'request': request})
return Response(serializer.data, status=status.HTTP_201_CREATED)
except IntegrityError as ex:
return Response(
dict(error=str(ex), detail=VERSION_ALREADY_EXISTS.format(version)),
status=status.HTTP_409_CONFLICT
)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_queryset(self):
queryset = super().get_queryset()
if self.released_filter is not None:
queryset = queryset.filter(released=self.released_filter)
return queryset.order_by('-created_at')
class SourceLatestVersionRetrieveUpdateView(SourceVersionBaseView, RetrieveAPIView, UpdateAPIView):
serializer_class = SourceVersionDetailSerializer
permission_classes = (CanViewConceptDictionaryVersion,)
def get_object(self, queryset=None):
obj = self.get_queryset().first()
if not obj:
raise Http404
self.check_object_permissions(self.request, obj)
return obj
def get_queryset(self):
queryset = super().get_queryset().filter(released=True)
return queryset.order_by('-created_at')
def update(self, request, *args, **kwargs):
self.object = self.get_object()
head = self.object.head
if not head:
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
serializer = self.get_serializer(self.object, data=request.data, partial=True)
if serializer.is_valid():
self.object = serializer.save(force_update=True)
if serializer.is_valid():
serializer = SourceVersionDetailSerializer(self.object, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class SourceVersionRetrieveUpdateDestroyView(SourceVersionBaseView, RetrieveAPIView, UpdateAPIView):
serializer_class = SourceVersionDetailSerializer
def get_permissions(self):
if self.request.method == 'GET':
return [CanViewConceptDictionaryVersion()]
return [HasAccessToVersionedObject()]
def get_object(self, queryset=None):
instance = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, instance)
return instance
def update(self, request, *args, **kwargs):
self.object = self.get_object()
head = self.object.head
if not head:
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
external_id = get(request.data, 'version_external_id')
if external_id:
request.data['external_id'] = external_id
serializer = self.get_serializer(self.object, data=request.data, partial=True)
if serializer.is_valid():
self.object = serializer.save(force_update=True)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, _, **kwargs): # pylint: disable=unused-argument
instance = self.get_object()
try:
instance.delete()
except ValidationError as ex:
return Response(ex.message_dict, status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_204_NO_CONTENT)
class SourceExtrasBaseView(SourceBaseView):
def get_object(self, queryset=None):
return self.get_queryset().filter(version=HEAD).first()
class SourceExtrasView(SourceExtrasBaseView, ListAPIView):
serializer_class = SourceDetailSerializer
def list(self, request, *args, **kwargs):
return Response(get(self.get_object(), 'extras', {}))
class SourceExtraRetrieveUpdateDestroyView(SourceExtrasBaseView, RetrieveUpdateDestroyAPIView):
serializer_class = SourceDetailSerializer
def retrieve(self, request, *args, **kwargs):
key = kwargs.get('extra')
instance = self.get_object()
extras = get(instance, 'extras', {})
if key in extras:
return Response({key: extras[key]})
return Response(dict(detail=NOT_FOUND), status=status.HTTP_404_NOT_FOUND)
def update(self, request, **kwargs): # pylint: disable=arguments-differ
key = kwargs.get('extra')
value = request.data.get(key)
if not value:
return Response([MUST_SPECIFY_EXTRA_PARAM_IN_BODY.format(key)], status=status.HTTP_400_BAD_REQUEST)
instance = self.get_object()
instance.extras = get(instance, 'extras', {})
instance.extras[key] = value
instance.comment = 'Updated extras: %s=%s.' % (key, value)
head = instance.get_head()
head.extras = get(head, 'extras', {})
head.extras.update(instance.extras)
instance.save()
head.save()
return Response({key: value})
def delete(self, request, *args, **kwargs):
key = kwargs.get('extra')
instance = self.get_object()
instance.extras = get(instance, 'extras', {})
if key in instance.extras:
del instance.extras[key]
instance.comment = 'Deleted extra %s.' % key
head = instance.get_head()
head.extras = get(head, 'extras', {})
del head.extras[key]
instance.save()
head.save()
return Response(status=status.HTTP_204_NO_CONTENT)
return Response(dict(detail=NOT_FOUND), status=status.HTTP_404_NOT_FOUND)
class SourceVersionProcessingView(SourceBaseView, ConceptContainerProcessingMixin):
serializer_class = SourceVersionDetailSerializer
resource = 'source'
class SourceVersionExportView(ConceptContainerExportMixin, SourceVersionBaseView):
entity = 'Source'
permission_classes = (CanViewConceptDictionary,)
serializer_class = SourceVersionExportSerializer
def handle_export_version(self):
version = self.get_object()
try:
export_source.delay(version.id)
return status.HTTP_202_ACCEPTED
except AlreadyQueued:
return status.HTTP_409_CONFLICT
class SourceHierarchyView(SourceBaseView, RetrieveAPIView):
serializer_class = SourceSummaryDetailSerializer
permission_classes = (CanViewConceptDictionary,)
def get_object(self, queryset=None):
instance = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, instance)
return instance
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
return Response(instance.hierarchy())
class SourceSummaryView(SourceBaseView, RetrieveAPIView):
serializer_class = SourceSummaryDetailSerializer
permission_classes = (CanViewConceptDictionary,)
def get_object(self, queryset=None):
instance = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, instance)
return instance
class SourceVersionSummaryView(SourceVersionBaseView, RetrieveAPIView):
serializer_class = SourceVersionSummaryDetailSerializer
permission_classes = (CanViewConceptDictionary,)
def get_object(self, queryset=None):
instance = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, instance)
return instance
class SourceLatestVersionSummaryView(SourceVersionBaseView, RetrieveAPIView, UpdateAPIView):
serializer_class = SourceVersionSummaryDetailSerializer
permission_classes = (CanViewConceptDictionary,)
def get_object(self, queryset=None):
obj = self.get_queryset().first()
if not obj:
raise Http404
self.check_object_permissions(self.request, obj)
return obj
def get_queryset(self):
queryset = super().get_queryset().filter(released=True)
return queryset.order_by('-created_at')
class SourceClientConfigsView(ResourceClientConfigsView):
lookup_field = 'source'
model = Source
queryset = Source.objects.filter(is_active=True, version='HEAD')
permission_classes = (CanViewConceptDictionary, )