-
Notifications
You must be signed in to change notification settings - Fork 32
/
views.py
278 lines (219 loc) · 9.63 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
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from elasticsearch_dsl import Q
from pydash import get
from rest_framework import response, generics, status
from core.common.constants import SEARCH_PARAM, ES_RESULTS_MAX_LIMIT, LIST_DEFAULT_LIMIT, CSV_DEFAULT_LIMIT, LIMIT_PARAM
from core.common.mixins import PathWalkerMixin
from core.common.utils import compact_dict_by_values, to_snake_case
from core.concepts.permissions import CanViewParentDictionary
from core.orgs.constants import ORG_OBJECT_TYPE
from core.users.constants import USER_OBJECT_TYPE
class BaseAPIView(generics.GenericAPIView, PathWalkerMixin):
"""
An extension of generics.GenericAPIView that:
1. Adds a hook for a post-initialize step
2. De-couples the lookup field name (in the URL) from the "filter by" field name (in the queryset)
3. Performs a soft delete on destroy()
"""
pk_field = 'mnemonic'
user_is_self = False
is_searchable = False
limit = LIST_DEFAULT_LIMIT
default_filters = dict(is_active=True)
sort_asc_param = 'sortAsc'
sort_desc_param = 'sortDesc'
default_qs_sort_attr = '-updated_at'
exact_match = 'exact_match'
facet_class = None
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
self.initialize(request, request.path_info, **kwargs)
def initialize(self, request, path_info_segment, **kwargs): # pylint: disable=unused-argument
self.user_is_self = kwargs.pop('user_is_self', False)
self.limit = request.query_params.dict().get(LIMIT_PARAM, LIST_DEFAULT_LIMIT)
def get_object(self, queryset=None): # pylint: disable=arguments-differ
# Determine the base queryset to use.
if queryset is None:
queryset = self.filter_queryset(self.get_queryset())
else:
pass # Deprecation warning
# Perform the lookup filtering.
lookup = self.kwargs.get(self.lookup_field, None)
filter_kwargs = {self.pk_field: lookup}
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
def destroy(self, request, *args, **kwargs): # pylint: disable=unused-argument
obj = self.get_object()
obj.soft_delete()
return response.Response(status=status.HTTP_204_NO_CONTENT)
def get_host_url(self):
return self.request.META['wsgi.url_scheme'] + '://' + self.request.get_host()
def head(self, request, **kwargs): # pylint: disable=unused-argument
res = HttpResponse()
res['num_found'] = self.filter_queryset(self.get_queryset()).count()
return res
def filter_queryset(self, queryset):
if self.is_searchable and self.should_perform_es_search():
return self.get_search_results_qs().filter(id__in=queryset.values_list('id'))
return super().filter_queryset(queryset).order_by(self.default_qs_sort_attr)
def get_sort_and_desc(self):
query_params = self.request.query_params.dict()
sort_field = query_params.get(self.sort_desc_param)
if sort_field is not None:
return sort_field, True
sort_field = query_params.get(self.sort_asc_param)
if sort_field is not None:
return sort_field, False
return None, None
def is_valid_sort(self, field):
if not self.es_fields or not field:
return False
if field in self.es_fields:
attrs = self.es_fields[field]
return attrs.get('sortable', False)
return False
def is_exact_match_on(self):
return self.request.query_params.dict().get(self.exact_match, None) == 'on'
def get_default_sort(self):
for field in self.es_fields:
attrs = self.es_fields[field]
if 'sortable' in attrs and 'default' in attrs:
prefix = '-' if attrs['default'] == 'desc' else ''
return prefix + field
return None
def get_searchable_fields(self):
return [field for field, config in get(self, 'es_fields', dict()).items() if config.get('filterable', False)]
def get_exact_search_fields(self):
return [field for field, config in get(self, 'es_fields', dict()).items() if config.get('exact', False)]
def get_search_string(self):
return self.request.query_params.dict().get(SEARCH_PARAM, '')
def get_wildcard_search_string(self):
return "*{}*".format(self.get_search_string())
def get_sort_attr(self):
sort_field, desc = self.get_sort_and_desc()
if self.is_valid_sort(sort_field):
if desc:
sort_field = '-' + sort_field
return sort_field
return dict(_score=dict(order="desc"))
def get_exact_search_criterion(self):
search_str = self.get_search_string()
def get_query(attr):
return Q('match', **{attr: search_str})
exact_search_fields = self.get_exact_search_fields()
criterion = get_query(exact_search_fields.pop())
for field in exact_search_fields:
criterion |= get_query(field)
return criterion
def get_faceted_criterion(self):
filters = self.get_faceted_filters()
def get_query(attr, val):
vals = val.split(',')
criteria = Q('match', **{attr: vals.pop()})
for _val in vals:
criteria |= Q('match', **{attr: _val})
return criteria
if filters:
first_filter = filters.popitem()
criterion = get_query(first_filter[0], first_filter[1])
for field, value in filters.items():
criterion &= get_query(field, value)
return criterion
def get_faceted_filters(self):
faceted_filters = dict()
faceted_fields = self.get_faceted_fields()
query_params = {to_snake_case(k): v for k, v in self.request.query_params.dict().items()}
for field in faceted_fields:
if field in query_params:
faceted_filters[field] = query_params[field]
return faceted_filters
def get_faceted_fields(self):
return [field for field, config in get(self, 'es_fields', dict()).items() if config.get('facet', False)]
def get_facet_filters_from_kwargs(self):
kwargs = self.kwargs
filters = dict()
if 'user' in kwargs:
filters['ownerType'] = USER_OBJECT_TYPE
filters['owner'] = kwargs['user']
if 'org' in kwargs:
filters['ownerType'] = ORG_OBJECT_TYPE
filters['owner'] = kwargs['org']
if 'source' in kwargs:
filters['source'] = kwargs['source']
if 'collection' in kwargs:
filters['collection'] = kwargs['collection']
return filters
def get_facets(self):
facets = dict()
if self.should_include_facets() and self.facet_class:
filters = {**self.default_filters, **self.get_facet_filters_from_kwargs()}
searcher = self.facet_class( # pylint: disable=not-callable
self.get_search_string(), filters=filters, exact_match=self.is_exact_match_on()
)
facets = searcher.execute().facets.to_dict()
return facets
def get_search_results(self):
results = None
if self.should_perform_es_search():
results = self.document_model.search()
for field, value in self.default_filters.items():
results = results.filter("match", **{field: value})
faceted_criterion = self.get_faceted_criterion()
if faceted_criterion:
results = results.query(faceted_criterion)
if self.is_exact_match_on():
results = results.query(self.get_exact_search_criterion())
else:
results = results.filter(
"query_string", query=self.get_wildcard_search_string(), fields=self.get_searchable_fields()
)
results = results[0:ES_RESULTS_MAX_LIMIT]
sort_field = self.get_sort_attr()
if sort_field:
results = results.sort(sort_field)
return results
def get_search_results_qs(self):
queryset = None
search_results = self.get_search_results()
if search_results:
queryset = search_results.to_queryset()
return queryset
def should_perform_es_search(self):
return bool(
SEARCH_PARAM in self.request.query_params and
self.document_model and
self.get_searchable_fields()
)
class SourceChildCommonBaseView(BaseAPIView):
lookup_field = None
model = None
queryset = None
params = None
document_model = None
es_fields = dict()
pk_field = 'mnemonic'
permission_classes = (CanViewParentDictionary, )
is_searchable = True
default_filters = dict(is_active=True, is_latest_version=True)
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
self.__set_params()
def get_filter_params(self):
if self.params:
return self.params
self.__set_params()
return self.params
def __get_params(self):
kwargs = self.kwargs.copy()
query_params = self.request.query_params.dict().copy()
kwargs.update(query_params)
return compact_dict_by_values(kwargs)
def __set_params(self):
self.params = self.__get_params()
if self.params:
self.limit = CSV_DEFAULT_LIMIT if self.params.get('csv') else int(self.params.get(
LIMIT_PARAM, LIST_DEFAULT_LIMIT
))