Coverage for apis_core/generic/helpers.py: 33%

75 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-06-25 10:00 +0000

1import functools 

2import logging 

3 

4from django.conf import settings 

5from django.contrib.auth import get_permission_codename 

6from django.db.models import CharField, Model, Q, TextField 

7from django.utils import module_loading 

8 

9logger = logging.getLogger(__name__) 

10 

11 

12def default_search_fields(model, field_names=None): 

13 """ 

14 Retrieve the default model fields to use for a search operation 

15 By default those are all the CharFields and TextFields of a model. 

16 It is also possible to define those fields on the model using the 

17 `_default_search_fields` attribute. 

18 The method also takes a `field_names` argument to override the list 

19 of fields. 

20 """ 

21 default_types = (CharField, TextField) 

22 fields = [ 

23 field for field in model._meta.get_fields() if isinstance(field, default_types) 

24 ] 

25 # check if the model has a `_default_search_fields` 

26 # list and use that as searchfields 

27 if isinstance(getattr(model, "_default_search_fields", None), list): 

28 fields = [ 

29 model._meta.get_field(field) for field in model._default_search_fields 

30 ] 

31 # if `fields_to_search` is a list, use that 

32 if isinstance(field_names, list): 

33 fields = [model._meta.get_field(field) for field in field_names] 

34 return fields 

35 

36 

37def generate_search_filter(model, query, fields_to_search=None, prefix=""): 

38 """ 

39 Generate a default search filter that searches for the `query` 

40 This helper can be used by autocomplete querysets if nothing 

41 fancier is needed. 

42 If the `prefix` is set, the field names will be prefixed with that string - 

43 this can be useful if you want to use the `generate_search_filter` in a 

44 `Q` combined query while searching over multiple models. 

45 """ 

46 if isinstance(query, str): 

47 query = query.split() 

48 

49 _fields_to_search = [ 

50 field.name for field in default_search_fields(model, fields_to_search) 

51 ] 

52 

53 q = Q() 

54 

55 for token in query: 

56 q &= functools.reduce( 

57 lambda acc, field_name: acc 

58 | Q(**{f"{prefix}{field_name}__icontains": token}), 

59 _fields_to_search, 

60 Q(), 

61 ) 

62 return q 

63 

64 

65@functools.lru_cache 

66def mro_paths(model): 

67 """ 

68 Create a list of MRO classes for a Django model 

69 """ 

70 paths = [] 

71 if model is not None: 

72 for cls in filter(lambda x: x not in Model.mro(), model.mro()): 

73 paths.append(cls.__module__.split(".")[:-1] + [cls.__name__]) 

74 return paths 

75 

76 

77@functools.lru_cache 

78def template_names_via_mro(model, suffix=""): 

79 """ 

80 Use the MRO to generate a list of template names for a model 

81 """ 

82 mro_prefix_list = ["/".join(prefix) for prefix in mro_paths(model)] 

83 return [f"{prefix.lower()}{suffix}" for prefix in mro_prefix_list] 

84 

85 

86@functools.lru_cache 

87def permission_fullname(action: str, model: object) -> str: 

88 permission_codename = get_permission_codename(action, model._meta) 

89 return f"{model._meta.app_label}.{permission_codename}" 

90 

91 

92@functools.lru_cache 

93def module_paths(model, path: str = "", suffix: str = "") -> list: 

94 paths = list(map(lambda x: x[:-1] + [path] + x[-1:], mro_paths(model))) 

95 prepends = [] 

96 for prepend in getattr(settings, "ADDITIONAL_MODULE_LOOKUP_PATHS", []): 

97 prepends.extend( 

98 list(map(lambda x: prepend.split(".") + [path] + x[-1:], mro_paths(model))) 

99 ) 

100 classes = tuple(".".join(prefix) + suffix for prefix in prepends + paths) 

101 return classes 

102 

103 

104@functools.lru_cache 

105def makeclassprefix(string: str) -> str: 

106 string = "".join([c if c.isidentifier() else " " for c in string]) 

107 string = "".join([word.strip().capitalize() for word in string.split(" ")]) 

108 return string 

109 

110 

111@functools.lru_cache 

112def import_string(dotted_path): 

113 try: 

114 return module_loading.import_string(dotted_path) 

115 except (ModuleNotFoundError, ImportError) as e: 

116 logger.debug("Could not load %s: %s", dotted_path, e) 

117 return False 

118 

119 

120@functools.lru_cache 

121def first_member_match(dotted_path_list: tuple[str], fallback=None) -> object: 

122 logger.debug("Looking for matching class in %s", dotted_path_list) 

123 pathgen = map(import_string, dotted_path_list) 

124 result = next(filter(bool, pathgen), None) 

125 if result: 

126 logger.debug("Found matching attribute/class in %s", result) 

127 else: 

128 logger.debug("Found nothing, returning fallback: %s", fallback) 

129 return result or fallback 

130 

131 

132def split_and_strip_parameter(params: [str]) -> [str]: 

133 """ 

134 Clean a URI param list type 

135 This method iterates through a list of strings. It looks if 

136 the items contain a comma separated list of items and then splits 

137 those and also runs strip on all those items. 

138 So out of ["foo.bar", "bar.faz, faz.foo"] it 

139 creates a list ["foo.bar", "bar.faz", "faz.foo"] 

140 """ 

141 newlist = [] 

142 for param in params: 

143 subparams = map(str.strip, param.split(",")) 

144 newlist.extend(subparams) 

145 return newlist 

146 

147 

148def string_to_bool(string: str = "false") -> bool: 

149 """ 

150 Convert a string to a boolean representing its semantic value 

151 """ 

152 return string.lower() == "true"