| 1 |
import inspect |
| 2 |
import warnings |
| 3 |
from collections import defaultdict, namedtuple |
| 4 |
from sys import version_info |
| 5 |
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple |
| 6 |
|
| 7 |
import pydantic |
| 8 |
from django.http import HttpResponse |
| 9 |
from pydantic.fields import FieldInfo |
| 10 |
from pydantic_core import PydanticUndefined |
| 11 |
from typing_extensions import Annotated, get_args, get_origin |
| 12 |
|
| 13 |
from ninja import UploadedFile |
| 14 |
from ninja.compatibility.util import UNION_TYPES |
| 15 |
from ninja.errors import ConfigError |
| 16 |
from ninja.params.models import ( |
| 17 |
Body, |
| 18 |
File, |
| 19 |
Form, |
| 20 |
Param, |
| 21 |
Path, |
| 22 |
Query, |
| 23 |
TModel, |
| 24 |
TModels, |
| 25 |
_MultiPartBody, |
| 26 |
) |
| 27 |
from ninja.signature.utils import get_path_param_names, get_typed_signature |
| 28 |
from ninja.utils import is_optional_type |
| 29 |
|
| 30 |
__all__ = [ |
| 31 |
"ViewSignature", |
| 32 |
"is_pydantic_model", |
| 33 |
"is_collection_type", |
| 34 |
"detect_collection_fields", |
| 35 |
] |
| 36 |
|
| 37 |
FuncParam = namedtuple( |
| 38 |
"FuncParam", ["name", "alias", "source", "annotation", "is_collection"] |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
class ViewSignature: |
| 43 |
FLATTEN_PATH_SEP = ( |
| 44 |
"\x1e" |
| 45 |
) |
| 46 |
response_arg: Optional[str] = None |
| 47 |
|
| 48 |
def __init__(self, path: str, view_func: Callable[..., Any]) -> None: |
| 49 |
self.view_func = view_func |
| 50 |
self.signature = get_typed_signature(self.view_func) |
| 51 |
self.path = path |
| 52 |
self.path_params_names = get_path_param_names(path) |
| 53 |
self.docstring = inspect.cleandoc(view_func.__doc__ or "") |
| 54 |
self.has_kwargs = False |
| 55 |
|
| 56 |
self.params = [] |
| 57 |
for name, arg in self.signature.parameters.items(): |
| 58 |
if name == "request": |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
continue |
| 63 |
|
| 64 |
if arg.kind == arg.VAR_KEYWORD: |
| 65 |
|
| 66 |
self.has_kwargs = True |
| 67 |
continue |
| 68 |
|
| 69 |
if arg.kind == arg.VAR_POSITIONAL: |
| 70 |
|
| 71 |
continue |
| 72 |
|
| 73 |
if arg.annotation is HttpResponse: |
| 74 |
self.response_arg = name |
| 75 |
continue |
| 76 |
|
| 77 |
if ( |
| 78 |
arg.annotation is inspect.Parameter.empty |
| 79 |
and isinstance(arg.default, type) |
| 80 |
and issubclass(arg.default, pydantic.BaseModel) |
| 81 |
): |
| 82 |
raise ConfigError( |
| 83 |
f"Looks like you are using `{name}={arg.default.__name__}` instead of `{name}: {arg.default.__name__}` (annotation)" |
| 84 |
) |
| 85 |
|
| 86 |
func_param = self._get_param_type(name, arg) |
| 87 |
self.params.append(func_param) |
| 88 |
|
| 89 |
if hasattr(view_func, "_ninja_contribute_args"): |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
for p_name, p_type, p_source in view_func._ninja_contribute_args: |
| 94 |
self.params.append( |
| 95 |
FuncParam(p_name, p_source.alias or p_name, p_source, p_type, False) |
| 96 |
) |
| 97 |
|
| 98 |
self.models: TModels = self._create_models() |
| 99 |
|
| 100 |
self._validate_view_path_params() |
| 101 |
|
| 102 |
def _validate_view_path_params(self) -> None: |
| 103 |
"""verify all path params are present in the path model fields""" |
| 104 |
if self.path_params_names: |
| 105 |
path_model = next( |
| 106 |
(m for m in self.models if m.__ninja_param_source__ == "path"), None |
| 107 |
) |
| 108 |
missing = tuple( |
| 109 |
sorted( |
| 110 |
name |
| 111 |
for name in self.path_params_names |
| 112 |
if not (path_model and name in path_model.__ninja_flatten_map__) |
| 113 |
) |
| 114 |
) |
| 115 |
if missing: |
| 116 |
warnings.warn_explicit( |
| 117 |
UserWarning( |
| 118 |
f"Field(s) {missing} are in the view path, but were not found in the view signature." |
| 119 |
), |
| 120 |
category=None, |
| 121 |
filename=inspect.getfile(self.view_func), |
| 122 |
lineno=inspect.getsourcelines(self.view_func)[1], |
| 123 |
source=None, |
| 124 |
) |
| 125 |
|
| 126 |
def _create_models(self) -> TModels: |
| 127 |
params_by_source_cls: Dict[Any, List[FuncParam]] = defaultdict(list) |
| 128 |
for param in self.params: |
| 129 |
param_source_cls = type(param.source) |
| 130 |
params_by_source_cls[param_source_cls].append(param) |
| 131 |
|
| 132 |
is_multipart_response_with_body = Body in params_by_source_cls and ( |
| 133 |
File in params_by_source_cls or Form in params_by_source_cls |
| 134 |
) |
| 135 |
if is_multipart_response_with_body: |
| 136 |
params_by_source_cls[_MultiPartBody] = params_by_source_cls.pop(Body) |
| 137 |
|
| 138 |
result = [] |
| 139 |
for param_cls, args in params_by_source_cls.items(): |
| 140 |
cls_name: str = param_cls.__name__ + "Params" |
| 141 |
attrs = {i.name: i.source for i in args} |
| 142 |
attrs["__ninja_param_source__"] = param_cls._param_source() |
| 143 |
attrs["__ninja_flatten_map_reverse__"] = {} |
| 144 |
|
| 145 |
if attrs["__ninja_param_source__"] == "file": |
| 146 |
pass |
| 147 |
|
| 148 |
elif attrs["__ninja_param_source__"] in { |
| 149 |
"form", |
| 150 |
"query", |
| 151 |
"header", |
| 152 |
"cookie", |
| 153 |
"path", |
| 154 |
}: |
| 155 |
flatten_map = self._args_flatten_map(args) |
| 156 |
attrs["__ninja_flatten_map__"] = flatten_map |
| 157 |
attrs["__ninja_flatten_map_reverse__"] = { |
| 158 |
v: (k,) for k, v in flatten_map.items() |
| 159 |
} |
| 160 |
|
| 161 |
else: |
| 162 |
assert attrs["__ninja_param_source__"] == "body" |
| 163 |
if is_multipart_response_with_body: |
| 164 |
attrs["__ninja_body_params__"] = { |
| 165 |
i.alias: i.annotation for i in args |
| 166 |
} |
| 167 |
else: |
| 168 |
|
| 169 |
attrs["__read_from_single_attr__"] = ( |
| 170 |
args[0].name if len(args) == 1 else None |
| 171 |
) |
| 172 |
|
| 173 |
|
| 174 |
attrs["__annotations__"] = {i.name: i.annotation for i in args} |
| 175 |
|
| 176 |
|
| 177 |
attrs["__ninja_collection_fields__"] = detect_collection_fields( |
| 178 |
args, attrs.get("__ninja_flatten_map__", {}) |
| 179 |
) |
| 180 |
|
| 181 |
base_cls = param_cls._model |
| 182 |
model_cls = type(cls_name, (base_cls,), attrs) |
| 183 |
|
| 184 |
result.append(model_cls) |
| 185 |
return result |
| 186 |
|
| 187 |
def _args_flatten_map(self, args: List[FuncParam]) -> Dict[str, Tuple[str, ...]]: |
| 188 |
flatten_map = {} |
| 189 |
arg_names: Any = {} |
| 190 |
for arg in args: |
| 191 |
if is_pydantic_model(arg.annotation): |
| 192 |
for name, path in self._model_flatten_map(arg.annotation, arg.alias): |
| 193 |
if name in flatten_map: |
| 194 |
raise ConfigError( |
| 195 |
f"Duplicated name: '{name}' in params: '{arg_names[name]}' & '{arg.name}'" |
| 196 |
) |
| 197 |
flatten_map[name] = tuple(path.split(self.FLATTEN_PATH_SEP)) |
| 198 |
arg_names[name] = arg.name |
| 199 |
else: |
| 200 |
name = arg.alias |
| 201 |
if name in flatten_map: |
| 202 |
raise ConfigError( |
| 203 |
f"Duplicated name: '{name}' also in '{arg_names[name]}'" |
| 204 |
) |
| 205 |
flatten_map[name] = (name,) |
| 206 |
arg_names[name] = name |
| 207 |
|
| 208 |
return flatten_map |
| 209 |
|
| 210 |
def _model_flatten_map(self, model: TModel, prefix: str) -> Generator: |
| 211 |
model = _unwrap_union_model(model) |
| 212 |
field: FieldInfo |
| 213 |
for attr, field in model.model_fields.items(): |
| 214 |
field_name = field.alias or attr |
| 215 |
name = f"{prefix}{self.FLATTEN_PATH_SEP}{field_name}" |
| 216 |
if is_pydantic_model(field.annotation): |
| 217 |
yield from self._model_flatten_map(field.annotation, name) |
| 218 |
else: |
| 219 |
yield field_name, name |
| 220 |
|
| 221 |
def _get_param_type(self, name: str, arg: inspect.Parameter) -> FuncParam: |
| 222 |
|
| 223 |
annotation = arg.annotation |
| 224 |
default = arg.default |
| 225 |
|
| 226 |
if get_origin(annotation) is Annotated: |
| 227 |
args = get_args(annotation) |
| 228 |
if isinstance(args[-1], Param): |
| 229 |
prev_default = default |
| 230 |
if len(args) == 2: |
| 231 |
annotation, default = args |
| 232 |
else: |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
if version_info >= (3, 9): |
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
annotation, default = Annotated[args[:-1]], args[-1] |
| 242 |
else: |
| 243 |
raise NotImplementedError( |
| 244 |
"This definition requires Python version 3.9+" |
| 245 |
) |
| 246 |
if prev_default != self.signature.empty: |
| 247 |
default.default = prev_default |
| 248 |
|
| 249 |
if annotation == self.signature.empty: |
| 250 |
if default == self.signature.empty: |
| 251 |
annotation = str |
| 252 |
else: |
| 253 |
if isinstance(default, Param): |
| 254 |
annotation = type(default.default) |
| 255 |
else: |
| 256 |
annotation = type(default) |
| 257 |
|
| 258 |
if annotation == PydanticUndefined.__class__: |
| 259 |
|
| 260 |
annotation = str |
| 261 |
|
| 262 |
if annotation == type(None) or annotation == type(Ellipsis): |
| 263 |
annotation = str |
| 264 |
|
| 265 |
is_collection = is_collection_type(annotation) |
| 266 |
|
| 267 |
if annotation == UploadedFile or ( |
| 268 |
is_collection and annotation.__args__[0] == UploadedFile |
| 269 |
): |
| 270 |
|
| 271 |
if default == self.signature.empty or default is None: |
| 272 |
default = default == self.signature.empty and ... or default |
| 273 |
return FuncParam(name, name, File(default), annotation, is_collection) |
| 274 |
|
| 275 |
|
| 276 |
if isinstance(default, Param): |
| 277 |
param_source = default |
| 278 |
|
| 279 |
|
| 280 |
elif name in self.path_params_names: |
| 281 |
assert ( |
| 282 |
default == self.signature.empty |
| 283 |
), f"'{name}' is a path param, default not allowed" |
| 284 |
param_source = Path(...) |
| 285 |
|
| 286 |
|
| 287 |
elif is_collection or is_pydantic_model(annotation): |
| 288 |
if default == self.signature.empty: |
| 289 |
param_source = Body(...) |
| 290 |
else: |
| 291 |
param_source = Body(default) |
| 292 |
|
| 293 |
|
| 294 |
else: |
| 295 |
if default == self.signature.empty: |
| 296 |
param_source = Query(...) |
| 297 |
else: |
| 298 |
param_source = Query(default) |
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
if default is None and not is_optional_type(annotation): |
| 303 |
annotation = Optional[annotation] |
| 304 |
|
| 305 |
return FuncParam( |
| 306 |
name, param_source.alias or name, param_source, annotation, is_collection |
| 307 |
) |
| 308 |
|
| 309 |
|
| 310 |
def _unwrap_union_model(annotation: Any) -> Any: |
| 311 |
"""If annotation is a Union containing a pydantic model, return that model class.""" |
| 312 |
if get_origin(annotation) in UNION_TYPES: |
| 313 |
for arg in get_args(annotation): |
| 314 |
if arg is not type(None) and is_pydantic_model(arg): |
| 315 |
return arg |
| 316 |
return annotation |
| 317 |
|
| 318 |
|
| 319 |
def is_pydantic_model(cls: Any) -> bool: |
| 320 |
try: |
| 321 |
origin = get_origin(cls) |
| 322 |
|
| 323 |
|
| 324 |
if origin is Annotated: |
| 325 |
args = get_args(cls) |
| 326 |
return is_pydantic_model(args[0]) |
| 327 |
|
| 328 |
|
| 329 |
if origin in UNION_TYPES: |
| 330 |
return any(issubclass(arg, pydantic.BaseModel) for arg in get_args(cls)) |
| 331 |
return issubclass(cls, pydantic.BaseModel) |
| 332 |
except TypeError: |
| 333 |
return False |
| 334 |
|
| 335 |
|
| 336 |
def is_collection_type(annotation: Any) -> bool: |
| 337 |
origin = get_origin(annotation) |
| 338 |
|
| 339 |
if origin in UNION_TYPES: |
| 340 |
for arg in get_args(annotation): |
| 341 |
if is_collection_type(arg): |
| 342 |
return True |
| 343 |
return False |
| 344 |
|
| 345 |
collection_types = (List, list, set, tuple) |
| 346 |
if origin is None: |
| 347 |
return ( |
| 348 |
isinstance(annotation, collection_types) |
| 349 |
if not isinstance(annotation, type) |
| 350 |
else issubclass(annotation, collection_types) |
| 351 |
) |
| 352 |
else: |
| 353 |
return origin in collection_types |
| 354 |
|
| 355 |
|
| 356 |
def detect_collection_fields( |
| 357 |
args: List[FuncParam], flatten_map: Dict[str, Tuple[str, ...]] |
| 358 |
) -> List[str]: |
| 359 |
""" |
| 360 |
Django QueryDict has values that are always lists, so we need to help django ninja to understand |
| 361 |
better the input parameters if it's a list or a single value |
| 362 |
This method detects attributes that should be treated by ninja as lists and returns this list as a result |
| 363 |
""" |
| 364 |
result = [i.alias or i.name for i in args if i.is_collection] |
| 365 |
|
| 366 |
if flatten_map: |
| 367 |
args_d = {arg.alias: arg for arg in args} |
| 368 |
for path in (p for p in flatten_map.values() if len(p) > 1): |
| 369 |
annotation_or_field: Any = args_d[path[0]].annotation |
| 370 |
for attr in path[1:]: |
| 371 |
if hasattr(annotation_or_field, "annotation"): |
| 372 |
annotation_or_field = annotation_or_field.annotation |
| 373 |
annotation_or_field = _unwrap_union_model(annotation_or_field) |
| 374 |
annotation_or_field = next( |
| 375 |
( |
| 376 |
a |
| 377 |
for a in annotation_or_field.model_fields.values() |
| 378 |
if a.alias == attr |
| 379 |
), |
| 380 |
annotation_or_field.model_fields.get(attr), |
| 381 |
) |
| 382 |
|
| 383 |
annotation_or_field = getattr( |
| 384 |
annotation_or_field, "outer_type_", annotation_or_field |
| 385 |
) |
| 386 |
|
| 387 |
|
| 388 |
annotation_or_field = annotation_or_field.annotation |
| 389 |
|
| 390 |
if is_collection_type(annotation_or_field): |
| 391 |
result.append(path[-1]) |
| 392 |
return result |