|
| 1 | +import inspect |
| 2 | +import operator |
| 3 | +from functools import reduce, wraps |
| 4 | +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Type |
| 5 | + |
| 6 | +from django.db.models import Q, QuerySet |
| 7 | +from django.db.models.constants import LOOKUP_SEP |
| 8 | +from ninja import Field, Query, Schema |
| 9 | +from ninja.constants import NOT_SET |
| 10 | + |
| 11 | +from ninja_extra.conf import settings |
| 12 | + |
| 13 | +if TYPE_CHECKING: # pragma: no cover |
| 14 | + from ninja_extra.controllers import ControllerBase |
| 15 | + |
| 16 | + |
| 17 | +class Search: |
| 18 | + |
| 19 | + class Input(Schema): |
| 20 | + search: Optional[str] = Field(None) |
| 21 | + |
| 22 | + lookup_prefixes = { |
| 23 | + '^': 'istartswith', |
| 24 | + '=': 'iexact', |
| 25 | + '@': 'search', |
| 26 | + '$': 'iregex', |
| 27 | + } |
| 28 | + input_source = Query(...) |
| 29 | + |
| 30 | + def __init__(self, search_fields: List[str], pass_parameter: Optional[str] = None) -> None: |
| 31 | + self.search_fields = search_fields |
| 32 | + self.pass_parameter = pass_parameter |
| 33 | + |
| 34 | + def search_queryset(self, queryset: QuerySet, searching: Input): |
| 35 | + if searching.search: |
| 36 | + search_terms = self.get_search_terms(searching.search) |
| 37 | + |
| 38 | + if not self.search_fields or not search_terms: |
| 39 | + return queryset |
| 40 | + |
| 41 | + orm_lookups = [self.construct_search(str(search_field)) for search_field in self.search_fields] |
| 42 | + conditions = [] |
| 43 | + for search_term in search_terms: |
| 44 | + queries = [Q(**{orm_lookup: search_term}) for orm_lookup in orm_lookups] |
| 45 | + conditions.append(reduce(operator.or_, queries)) |
| 46 | + queryset = queryset.filter(reduce(operator.and_, conditions)) |
| 47 | + return queryset |
| 48 | + |
| 49 | + def get_search_terms(self, value: str): |
| 50 | + if value: |
| 51 | + value = value.replace('\x00', '') # strip null characters |
| 52 | + value = value.replace(',', ' ') |
| 53 | + return value.split() |
| 54 | + return '' |
| 55 | + |
| 56 | + def construct_search(self, field_name): |
| 57 | + lookup = self.lookup_prefixes.get(field_name[0]) |
| 58 | + if lookup: |
| 59 | + field_name = field_name[1:] |
| 60 | + else: |
| 61 | + lookup = 'icontains' |
| 62 | + return LOOKUP_SEP.join([field_name, lookup]) |
| 63 | + |
| 64 | + |
| 65 | +def searching(func_or_searching_class: Type[Search] = NOT_SET, **searching_params: Any) -> Callable: |
| 66 | + isfunction = inspect.isfunction(func_or_searching_class) |
| 67 | + isnotset = func_or_searching_class == NOT_SET |
| 68 | + searching_class: Type[Search] = settings.SEARCHING_CLASS |
| 69 | + if isfunction: |
| 70 | + return _inject_searcherator(func_or_searching_class, searching_class) |
| 71 | + if not isnotset: |
| 72 | + searching_class = func_or_searching_class |
| 73 | + |
| 74 | + def wrapper(func: Callable[..., Any]) -> Any: |
| 75 | + return _inject_searcherator(func, searching_class, **searching_params) |
| 76 | + |
| 77 | + return wrapper |
| 78 | + |
| 79 | + |
| 80 | +def _inject_searcherator( |
| 81 | + func: Callable[..., Any], |
| 82 | + searching_class: Type[Search], |
| 83 | + **searching_params: Any, |
| 84 | +) -> Callable[..., Any]: |
| 85 | + searcherator: Search = searching_class(**searching_params) |
| 86 | + searcherator_kwargs_name = "searching" |
| 87 | + _ninja_contribute_args: List[Tuple] = getattr(func, "_ninja_contribute_args", []) |
| 88 | + |
| 89 | + @wraps(func) |
| 90 | + def view_with_searching(controller: "ControllerBase", *args: Any, **kw: Any) -> Any: |
| 91 | + func_kwargs = dict(**kw) |
| 92 | + searching = func_kwargs.pop(searcherator_kwargs_name) |
| 93 | + if searcherator.pass_parameter: |
| 94 | + func_kwargs[searcherator.pass_parameter] = searching_params |
| 95 | + items = func(controller, *args, **func_kwargs) |
| 96 | + return searcherator.search_queryset(items, searching) |
| 97 | + |
| 98 | + _ninja_contribute_args.append(( |
| 99 | + searcherator_kwargs_name, |
| 100 | + searcherator.Input, |
| 101 | + searcherator.input_source, |
| 102 | + )) |
| 103 | + view_with_searching._ninja_contribute_args = _ninja_contribute_args |
| 104 | + return view_with_searching |
0 commit comments