2021-10-21 08:16:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
from typing import Callable
|
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2021-10-21 08:16:50 +00:00
|
|
|
from rest_framework.decorators import action
|
|
|
|
from rest_framework.request import Request
|
2023-03-10 07:52:07 +00:00
|
|
|
from rest_framework.response import Response
|
2021-10-21 08:16:50 +00:00
|
|
|
|
2024-07-02 08:26:44 +00:00
|
|
|
from common.const.http import POST, PUT
|
2021-10-21 08:16:50 +00:00
|
|
|
|
|
|
|
__all__ = ['SuggestionMixin', 'RenderToJsonMixin']
|
|
|
|
|
|
|
|
|
|
|
|
class SuggestionMixin:
|
|
|
|
suggestion_limit = 10
|
|
|
|
|
|
|
|
filter_queryset: Callable
|
|
|
|
get_queryset: Callable
|
|
|
|
paginate_queryset: Callable
|
|
|
|
get_serializer: Callable
|
|
|
|
get_paginated_response: Callable
|
|
|
|
|
2022-02-24 04:03:40 +00:00
|
|
|
@action(methods=['get'], detail=False, url_path='suggestions')
|
|
|
|
def match(self, request, *args, **kwargs):
|
2021-10-21 08:16:50 +00:00
|
|
|
queryset = self.filter_queryset(self.get_queryset())
|
|
|
|
queryset = queryset[:self.suggestion_limit]
|
|
|
|
page = self.paginate_queryset(queryset)
|
|
|
|
|
|
|
|
if page is not None:
|
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
|
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
|
|
|
|
class RenderToJsonMixin:
|
2024-07-02 08:26:44 +00:00
|
|
|
@action(methods=[POST, PUT], detail=False, url_path='render-to-json')
|
2022-03-14 09:53:21 +00:00
|
|
|
def render_to_json(self, request: Request, *args, **kwargs):
|
2021-10-21 08:16:50 +00:00
|
|
|
data = {
|
|
|
|
'title': (),
|
|
|
|
'data': request.data,
|
|
|
|
}
|
|
|
|
|
|
|
|
jms_context = getattr(request, 'jms_context', {})
|
|
|
|
column_title_field_pairs = jms_context.get('column_title_field_pairs', ())
|
|
|
|
data['title'] = column_title_field_pairs
|
|
|
|
|
|
|
|
if isinstance(request.data, (list, tuple)) and not any(request.data):
|
|
|
|
error = _("Request file format may be wrong")
|
|
|
|
return Response(data={"error": error}, status=400)
|
|
|
|
return Response(data=data)
|