|
| 1 | +from __future__ import annotations |
| 2 | +import abc |
| 3 | +import datetime |
| 4 | +import typing |
| 5 | + |
| 6 | +import elasticsearch_dsl as edsl |
| 7 | +from rest_framework import generics, exceptions as drf_exceptions |
| 8 | +from rest_framework.settings import api_settings as drf_settings |
| 9 | +from api.base.settings.defaults import REPORT_FILENAME_FORMAT |
| 10 | + |
| 11 | +if typing.TYPE_CHECKING: |
| 12 | + from rest_framework import serializers |
| 13 | + |
| 14 | +from api.base.filters import FilterMixin |
| 15 | +from api.base.views import JSONAPIBaseView |
| 16 | +from api.metrics.renderers import ( |
| 17 | + MetricsReportsCsvRenderer, |
| 18 | + MetricsReportsTsvRenderer, |
| 19 | + MetricsReportsJsonRenderer, |
| 20 | +) |
| 21 | +from api.base.pagination import ElasticsearchQuerySizeMaximumPagination, JSONAPIPagination |
| 22 | +from api.base.renderers import JSONAPIRenderer |
| 23 | + |
| 24 | + |
| 25 | +class ElasticsearchListView(FilterMixin, JSONAPIBaseView, generics.ListAPIView, abc.ABC): |
| 26 | + '''abstract view class using `elasticsearch_dsl.Search` as a queryset-analogue |
| 27 | +
|
| 28 | + builds a `Search` based on `self.get_default_search()` and the request's |
| 29 | + query parameters for filtering, sorting, and pagination -- fetches only |
| 30 | + the data required for the response, just like with a queryset! |
| 31 | + ''' |
| 32 | + serializer_class: type[serializers.BaseSerializer] # required on subclasses |
| 33 | + |
| 34 | + default_ordering: str | None = None # name of a serializer field, prepended with "-" for descending sort |
| 35 | + ordering_fields: frozenset[str] = frozenset() # serializer field names |
| 36 | + |
| 37 | + @abc.abstractmethod |
| 38 | + def get_default_search(self) -> edsl.Search | None: |
| 39 | + '''the base `elasticsearch_dsl.Search` for this list, based on url path |
| 40 | +
|
| 41 | + (common jsonapi query parameters will be considered automatically) |
| 42 | + ''' |
| 43 | + ... |
| 44 | + |
| 45 | + FILE_RENDERER_CLASSES = { |
| 46 | + MetricsReportsCsvRenderer, |
| 47 | + MetricsReportsTsvRenderer, |
| 48 | + MetricsReportsJsonRenderer, |
| 49 | + } |
| 50 | + |
| 51 | + def set_content_disposition(self, response, renderer: str): |
| 52 | + """Set the Content-Disposition header to prompt a file download with the appropriate filename. |
| 53 | +
|
| 54 | + Args: |
| 55 | + response: The HTTP response object to modify. |
| 56 | + renderer: The renderer instance used for the response, which determines the file extension. |
| 57 | + """ |
| 58 | + current_date = datetime.datetime.now().strftime('%Y-%m') |
| 59 | + |
| 60 | + if isinstance(renderer, JSONAPIRenderer): |
| 61 | + extension = 'json' |
| 62 | + else: |
| 63 | + extension = getattr(renderer, 'extension', renderer.format) |
| 64 | + |
| 65 | + filename = REPORT_FILENAME_FORMAT.format( |
| 66 | + view_name=self.view_name, |
| 67 | + date_created=current_date, |
| 68 | + extension=extension, |
| 69 | + ) |
| 70 | + |
| 71 | + response['Content-Disposition'] = f'attachment; filename="{filename}"' |
| 72 | + |
| 73 | + def finalize_response(self, request, response, *args, **kwargs): |
| 74 | + # Call the parent method to finalize the response first |
| 75 | + response = super().finalize_response(request, response, *args, **kwargs) |
| 76 | + # Check if this is a direct download request or file renderer classes, set to the Content-Disposition header |
| 77 | + # so filename and attachment for browser download |
| 78 | + if isinstance(request.accepted_renderer, tuple(self.FILE_RENDERER_CLASSES)): |
| 79 | + self.set_content_disposition(response, request.accepted_renderer) |
| 80 | + |
| 81 | + return response |
| 82 | + |
| 83 | + ### |
| 84 | + # beware! inheritance shenanigans below |
| 85 | + |
| 86 | + # override FilterMixin to disable all operators besides 'eq' and 'ne' |
| 87 | + MATCHABLE_FIELDS = () |
| 88 | + COMPARABLE_FIELDS = () |
| 89 | + DEFAULT_OPERATOR_OVERRIDES = {} |
| 90 | + # (if you want to add fulltext-search or range-filter support, remove the override |
| 91 | + # and update `__add_search_filter` to handle those operators -- tho note that the |
| 92 | + # underlying elasticsearch field mapping will need to be compatible with the query) |
| 93 | + |
| 94 | + # override DEFAULT_FILTER_BACKENDS rest_framework setting |
| 95 | + # (filtering handled in-view to reuse logic from FilterMixin) |
| 96 | + filter_backends = () |
| 97 | + |
| 98 | + # note: because elasticsearch_dsl.Search supports slicing and gives results when iterated on, |
| 99 | + # it works fine with default pagination |
| 100 | + |
| 101 | + # override rest_framework.generics.GenericAPIView |
| 102 | + @property |
| 103 | + def pagination_class(self): |
| 104 | + """ |
| 105 | + When downloading a file assume no pagination is necessary unless the user specifies |
| 106 | + """ |
| 107 | + is_file_download = any( |
| 108 | + self.request.accepted_renderer.format == renderer.format |
| 109 | + for renderer in self.FILE_RENDERER_CLASSES |
| 110 | + ) |
| 111 | + # if it's a file download of the JSON respect default page size |
| 112 | + if is_file_download: |
| 113 | + return ElasticsearchQuerySizeMaximumPagination |
| 114 | + return JSONAPIPagination |
| 115 | + |
| 116 | + def get_queryset(self): |
| 117 | + _search = self.get_default_search() |
| 118 | + if _search is None: |
| 119 | + return [] |
| 120 | + # using parsing logic from FilterMixin (oddly nested dict and all) |
| 121 | + for _parsed_param in self.parse_query_params(self.request.query_params).values(): |
| 122 | + for _parsed_filter in _parsed_param.values(): |
| 123 | + _search = self.__add_search_filter( |
| 124 | + _search, |
| 125 | + elastic_field_name=_parsed_filter['source_field_name'], |
| 126 | + operator=_parsed_filter['op'], |
| 127 | + value=_parsed_filter['value'], |
| 128 | + ) |
| 129 | + return self.__add_sort(_search) |
| 130 | + |
| 131 | + ### |
| 132 | + # private methods |
| 133 | + |
| 134 | + def __add_sort(self, search: edsl.Search) -> edsl.Search: |
| 135 | + _elastic_sort = self.__get_elastic_sort() |
| 136 | + return (search if _elastic_sort is None else search.sort(_elastic_sort)) |
| 137 | + |
| 138 | + def __get_elastic_sort(self) -> str | None: |
| 139 | + _sort_param = self.request.query_params.get(drf_settings.ORDERING_PARAM, self.default_ordering) |
| 140 | + if not _sort_param: |
| 141 | + return None |
| 142 | + _sort_field, _ascending = ( |
| 143 | + (_sort_param[1:], False) |
| 144 | + if _sort_param.startswith('-') |
| 145 | + else (_sort_param, True) |
| 146 | + ) |
| 147 | + if _sort_field not in self.ordering_fields: |
| 148 | + raise drf_exceptions.ValidationError( |
| 149 | + f'invalid value for {drf_settings.ORDERING_PARAM} query param (valid values: {", ".join(self.ordering_fields)})', |
| 150 | + ) |
| 151 | + _serializer_field = self.get_serializer().fields[_sort_field] |
| 152 | + _elastic_sort_field = _serializer_field.source |
| 153 | + return (_elastic_sort_field if _ascending else f'-{_elastic_sort_field}') |
| 154 | + |
| 155 | + def __add_search_filter( |
| 156 | + self, |
| 157 | + search: edsl.Search, |
| 158 | + elastic_field_name: str, |
| 159 | + operator: str, |
| 160 | + value: str, |
| 161 | + ) -> edsl.Search: |
| 162 | + match operator: # operators from FilterMixin |
| 163 | + case 'eq': |
| 164 | + if value == '': |
| 165 | + return search.exclude('exists', field=elastic_field_name) |
| 166 | + return search.filter('term', **{elastic_field_name: value}) |
| 167 | + case 'ne': |
| 168 | + if value == '': |
| 169 | + return search.filter('exists', field=elastic_field_name) |
| 170 | + return search.exclude('term', **{elastic_field_name: value}) |
| 171 | + case _: |
| 172 | + raise NotImplementedError(f'unsupported filter operator "{operator}"') |
0 commit comments