| 1 |
import inspect |
| 2 |
import warnings |
| 3 |
from typing import ( |
| 4 |
TYPE_CHECKING, |
| 5 |
Any, |
| 6 |
Callable, |
| 7 |
Coroutine, |
| 8 |
Dict, |
| 9 |
Iterable, |
| 10 |
List, |
| 11 |
Optional, |
| 12 |
Sequence, |
| 13 |
Type, |
| 14 |
Union, |
| 15 |
cast, |
| 16 |
) |
| 17 |
|
| 18 |
import pydantic |
| 19 |
from asgiref.sync import async_to_sync, sync_to_async |
| 20 |
from django.http import ( |
| 21 |
HttpRequest, |
| 22 |
HttpResponse, |
| 23 |
HttpResponseNotAllowed, |
| 24 |
StreamingHttpResponse, |
| 25 |
) |
| 26 |
from django.http.response import HttpResponseBase |
| 27 |
from pydantic import BaseModel |
| 28 |
|
| 29 |
from ninja.compatibility.files import FIX_MIDDLEWARE_PATH, need_to_fix_request_files |
| 30 |
from ninja.compatibility.streaming import create_streaming_response |
| 31 |
from ninja.constants import NOT_SET, NOT_SET_TYPE |
| 32 |
from ninja.errors import ( |
| 33 |
AuthenticationError, |
| 34 |
ConfigError, |
| 35 |
Throttled, |
| 36 |
ValidationErrorContext, |
| 37 |
) |
| 38 |
from ninja.params.models import TModels |
| 39 |
from ninja.responses import Status |
| 40 |
from ninja.schema import Schema, pydantic_version |
| 41 |
from ninja.signature import ViewSignature, is_async |
| 42 |
from ninja.streaming import StreamFormat, _serialize_item, _StreamAlias |
| 43 |
from ninja.throttling import BaseThrottle |
| 44 |
from ninja.types import DictStrAny |
| 45 |
from ninja.utils import is_async_callable |
| 46 |
|
| 47 |
if TYPE_CHECKING: |
| 48 |
from ninja import NinjaAPI |
| 49 |
|
| 50 |
__all__ = ["Operation", "PathView", "ResponseObject"] |
| 51 |
|
| 52 |
|
| 53 |
class Operation: |
| 54 |
def __init__( |
| 55 |
self, |
| 56 |
path: str, |
| 57 |
methods: List[str], |
| 58 |
view_func: Callable, |
| 59 |
*, |
| 60 |
auth: Optional[Union[Sequence[Callable], Callable, NOT_SET_TYPE]] = NOT_SET, |
| 61 |
throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET, |
| 62 |
response: Any = NOT_SET, |
| 63 |
operation_id: Optional[str] = None, |
| 64 |
summary: Optional[str] = None, |
| 65 |
description: Optional[str] = None, |
| 66 |
tags: Optional[List[str]] = None, |
| 67 |
deprecated: Optional[bool] = None, |
| 68 |
by_alias: Optional[bool] = None, |
| 69 |
exclude_unset: Optional[bool] = None, |
| 70 |
exclude_defaults: Optional[bool] = None, |
| 71 |
exclude_none: Optional[bool] = None, |
| 72 |
include_in_schema: bool = True, |
| 73 |
url_name: Optional[str] = None, |
| 74 |
openapi_extra: Optional[Dict[str, Any]] = None, |
| 75 |
) -> None: |
| 76 |
self.is_async = False |
| 77 |
self.path: str = path |
| 78 |
self.methods: List[str] = methods |
| 79 |
self.view_func: Callable = view_func |
| 80 |
self.api: NinjaAPI = cast("NinjaAPI", None) |
| 81 |
self.csrf_exempt: bool = getattr(view_func, "csrf_exempt", False) |
| 82 |
if url_name is not None: |
| 83 |
self.url_name = url_name |
| 84 |
|
| 85 |
self.auth_param: Optional[Union[Sequence[Callable], Callable, object]] = auth |
| 86 |
self.auth_callbacks: Sequence[Callable] = [] |
| 87 |
self._set_auth(auth) |
| 88 |
|
| 89 |
if isinstance(throttle, BaseThrottle): |
| 90 |
throttle = [throttle] |
| 91 |
self.throttle_param = throttle |
| 92 |
self.throttle_objects: List[BaseThrottle] = [] |
| 93 |
if throttle is not NOT_SET: |
| 94 |
for th in throttle: |
| 95 |
assert isinstance( |
| 96 |
th, BaseThrottle |
| 97 |
), "Throttle should be an instance of BaseThrottle" |
| 98 |
self.throttle_objects.append(th) |
| 99 |
|
| 100 |
self.signature = ViewSignature(self.path, self.view_func) |
| 101 |
self.models: TModels = self.signature.models |
| 102 |
|
| 103 |
self.stream_format: Optional[Type[StreamFormat]] = None |
| 104 |
self.stream_item_model: Optional[Type[Schema]] = None |
| 105 |
self.response_models: Dict[Any, Any] |
| 106 |
if isinstance(response, _StreamAlias): |
| 107 |
self.stream_format = response.format_cls |
| 108 |
self.stream_item_model = self._create_response_model(response.item_type) |
| 109 |
self.response_models = {200: self.stream_item_model} |
| 110 |
elif response is NOT_SET: |
| 111 |
self.response_models = {200: NOT_SET} |
| 112 |
elif isinstance(response, dict): |
| 113 |
self.response_models = self._create_response_model_multiple(response) |
| 114 |
else: |
| 115 |
self.response_models = {200: self._create_response_model(response)} |
| 116 |
|
| 117 |
if need_to_fix_request_files(methods, self.models): |
| 118 |
raise ConfigError( |
| 119 |
f"Router '{path}' has method(s) {methods} that require fixing request.FILES. " |
| 120 |
f"Please add '{FIX_MIDDLEWARE_PATH}' to settings.MIDDLEWARE" |
| 121 |
) |
| 122 |
|
| 123 |
self.operation_id = operation_id |
| 124 |
self.summary = summary or self.view_func.__name__.title().replace("_", " ") |
| 125 |
self.description = description or self.signature.docstring |
| 126 |
self.tags = tags |
| 127 |
self.deprecated = deprecated |
| 128 |
self.include_in_schema = include_in_schema |
| 129 |
self.openapi_extra = openapi_extra |
| 130 |
|
| 131 |
|
| 132 |
self.by_alias = by_alias or False |
| 133 |
self.exclude_unset = exclude_unset or False |
| 134 |
self.exclude_defaults = exclude_defaults or False |
| 135 |
self.exclude_none = exclude_none or False |
| 136 |
|
| 137 |
if hasattr(view_func, "_ninja_contribute_to_operation"): |
| 138 |
|
| 139 |
callbacks: List[Callable] = view_func._ninja_contribute_to_operation |
| 140 |
for callback in callbacks: |
| 141 |
callback(self) |
| 142 |
|
| 143 |
def clone(self) -> "Operation": |
| 144 |
""" |
| 145 |
Create a fresh copy of this operation for binding to an API. |
| 146 |
|
| 147 |
This method is used when mounting the same router multiple times |
| 148 |
to ensure each mount has independent operation instances. |
| 149 |
""" |
| 150 |
|
| 151 |
cloned = object.__new__(self.__class__) |
| 152 |
|
| 153 |
|
| 154 |
cloned.is_async = self.is_async |
| 155 |
cloned.path = self.path |
| 156 |
cloned.methods = list(self.methods) |
| 157 |
cloned.view_func = self.view_func |
| 158 |
cloned.api = cast("NinjaAPI", None) |
| 159 |
cloned.csrf_exempt = self.csrf_exempt |
| 160 |
|
| 161 |
|
| 162 |
if hasattr(self, "url_name"): |
| 163 |
cloned.url_name = self.url_name |
| 164 |
|
| 165 |
|
| 166 |
cloned.auth_param = self.auth_param |
| 167 |
cloned.auth_callbacks = list(self.auth_callbacks) |
| 168 |
|
| 169 |
|
| 170 |
cloned.throttle_param = self.throttle_param |
| 171 |
cloned.throttle_objects = list(self.throttle_objects) |
| 172 |
|
| 173 |
|
| 174 |
cloned.signature = self.signature |
| 175 |
cloned.models = self.models |
| 176 |
|
| 177 |
|
| 178 |
cloned.stream_format = self.stream_format |
| 179 |
cloned.stream_item_model = self.stream_item_model |
| 180 |
|
| 181 |
|
| 182 |
cloned.response_models = dict(self.response_models) |
| 183 |
|
| 184 |
|
| 185 |
cloned.operation_id = self.operation_id |
| 186 |
cloned.summary = self.summary |
| 187 |
cloned.description = self.description |
| 188 |
cloned.tags = list(self.tags) if self.tags else None |
| 189 |
cloned.deprecated = self.deprecated |
| 190 |
cloned.include_in_schema = self.include_in_schema |
| 191 |
cloned.openapi_extra = dict(self.openapi_extra) if self.openapi_extra else None |
| 192 |
|
| 193 |
|
| 194 |
cloned.by_alias = self.by_alias |
| 195 |
cloned.exclude_unset = self.exclude_unset |
| 196 |
cloned.exclude_defaults = self.exclude_defaults |
| 197 |
cloned.exclude_none = self.exclude_none |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
if hasattr(self, "_run_decorators") and self._run_decorators: |
| 202 |
cloned._run_decorators = [] |
| 203 |
for deco in self._run_decorators: |
| 204 |
cloned.run = deco(cloned.run) |
| 205 |
cloned._run_decorators.append(deco) |
| 206 |
|
| 207 |
return cloned |
| 208 |
|
| 209 |
def run(self, request: HttpRequest, **kw: Any) -> HttpResponseBase: |
| 210 |
error = self._run_checks(request) |
| 211 |
if error: |
| 212 |
return error |
| 213 |
try: |
| 214 |
temporal_response = self.api.create_temporal_response(request) |
| 215 |
values = self._get_values(request, kw, temporal_response) |
| 216 |
result = self.view_func(request, **values) |
| 217 |
if self.stream_format: |
| 218 |
return self._stream_response(request, result, temporal_response) |
| 219 |
return self._result_to_response(request, result, temporal_response) |
| 220 |
except Exception as e: |
| 221 |
if isinstance(e, TypeError) and "required positional argument" in str(e): |
| 222 |
msg = "Did you fail to use functools.wraps() in a decorator?" |
| 223 |
msg = f"{e.args[0]}: {msg}" if e.args else msg |
| 224 |
e.args = (msg,) + e.args[1:] |
| 225 |
return self.api.on_exception(request, e) |
| 226 |
|
| 227 |
def _validate_stream_item(self, item: Any, request: HttpRequest) -> str: |
| 228 |
"""Validate a single stream item and return serialized JSON string.""" |
| 229 |
assert self.stream_item_model is not None |
| 230 |
resp_object = ResponseObject(item) |
| 231 |
validated = self.stream_item_model.model_validate( |
| 232 |
resp_object, context={"request": request, "response_status": 200} |
| 233 |
) |
| 234 |
|
| 235 |
model_dump_kwargs: Dict[str, Any] = {} |
| 236 |
if pydantic_version >= [2, 7]: |
| 237 |
|
| 238 |
model_dump_kwargs.update( |
| 239 |
context={"request": request, "response_status": 200} |
| 240 |
) |
| 241 |
|
| 242 |
result = validated.model_dump( |
| 243 |
by_alias=self.by_alias, |
| 244 |
exclude_unset=self.exclude_unset, |
| 245 |
exclude_defaults=self.exclude_defaults, |
| 246 |
exclude_none=self.exclude_none, |
| 247 |
**model_dump_kwargs, |
| 248 |
)["response"] |
| 249 |
return _serialize_item(result) |
| 250 |
|
| 251 |
def _stream_response( |
| 252 |
self, |
| 253 |
request: HttpRequest, |
| 254 |
generator: Any, |
| 255 |
temporal_response: HttpResponse, |
| 256 |
) -> StreamingHttpResponse: |
| 257 |
"""Create a StreamingHttpResponse from a sync generator.""" |
| 258 |
assert self.stream_format is not None |
| 259 |
fmt = self.stream_format |
| 260 |
|
| 261 |
def content_iter() -> Any: |
| 262 |
for item in generator: |
| 263 |
data = self._validate_stream_item(item, request) |
| 264 |
yield fmt.format_chunk(data) |
| 265 |
|
| 266 |
for key, value in temporal_response.items(): |
| 267 |
if key.lower() != "content-type": |
| 268 |
response[key] = value |
| 269 |
for cookie_name, cookie in temporal_response.cookies.items(): |
| 270 |
response.cookies[cookie_name] = cookie |
| 271 |
|
| 272 |
response = StreamingHttpResponse( |
| 273 |
content_iter(), |
| 274 |
content_type=fmt.media_type, |
| 275 |
status=temporal_response.status_code, |
| 276 |
) |
| 277 |
|
| 278 |
for key, value in fmt.response_headers().items(): |
| 279 |
response[key] = value |
| 280 |
return response |
| 281 |
|
| 282 |
def _set_auth( |
| 283 |
self, auth: Optional[Union[Sequence[Callable], Callable, object]] |
| 284 |
) -> None: |
| 285 |
if auth is not None and auth is not NOT_SET: |
| 286 |
self.auth_callbacks = isinstance(auth, Sequence) and auth or [auth] |
| 287 |
|
| 288 |
def _run_checks(self, request: HttpRequest) -> Optional[HttpResponse]: |
| 289 |
"Runs security/throttle checks for each operation" |
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
if self.csrf_exempt: |
| 294 |
|
| 295 |
request._ninja_csrf_exempt = True |
| 296 |
|
| 297 |
|
| 298 |
if self.auth_callbacks: |
| 299 |
error = self._run_authentication(request) |
| 300 |
if error: |
| 301 |
return error |
| 302 |
|
| 303 |
|
| 304 |
if self.throttle_objects: |
| 305 |
error = self._check_throttles(request) |
| 306 |
if error: |
| 307 |
return error |
| 308 |
|
| 309 |
return None |
| 310 |
|
| 311 |
def _run_authentication(self, request: HttpRequest) -> Optional[HttpResponse]: |
| 312 |
for callback in self.auth_callbacks: |
| 313 |
try: |
| 314 |
if is_async_callable(callback) or getattr(callback, "is_async", False): |
| 315 |
result = callback(request) |
| 316 |
if inspect.iscoroutine(result): |
| 317 |
result = async_to_sync(callback)(request) |
| 318 |
else: |
| 319 |
result = callback(request) |
| 320 |
except Exception as exc: |
| 321 |
return self.api.on_exception(request, exc) |
| 322 |
|
| 323 |
if result: |
| 324 |
request.auth = result |
| 325 |
return None |
| 326 |
return self.api.on_exception(request, AuthenticationError()) |
| 327 |
|
| 328 |
def _check_throttles(self, request: HttpRequest) -> Optional[HttpResponse]: |
| 329 |
throttle_durations = [] |
| 330 |
for throttle in self.throttle_objects: |
| 331 |
if not throttle.allow_request(request): |
| 332 |
throttle_durations.append(throttle.wait()) |
| 333 |
|
| 334 |
if throttle_durations: |
| 335 |
|
| 336 |
durations = [ |
| 337 |
duration for duration in throttle_durations if duration is not None |
| 338 |
] |
| 339 |
|
| 340 |
duration = max(durations, default=None) |
| 341 |
return self.api.on_exception(request, Throttled(wait=duration)) |
| 342 |
return None |
| 343 |
|
| 344 |
def _model_dump_kwargs(self, request: HttpRequest, status: int) -> Dict[str, Any]: |
| 345 |
kwargs: Dict[str, Any] = {} |
| 346 |
if pydantic_version >= [2, 7]: |
| 347 |
kwargs["context"] = {"request": request, "response_status": status} |
| 348 |
return kwargs |
| 349 |
|
| 350 |
def _result_to_response( |
| 351 |
self, request: HttpRequest, result: Any, temporal_response: HttpResponse |
| 352 |
) -> HttpResponseBase: |
| 353 |
""" |
| 354 |
The protocol for results |
| 355 |
- if HttpResponse - returns as is |
| 356 |
- if Status object - uses status code + body |
| 357 |
- if tuple with 2 elements - means http_code + body (deprecated) |
| 358 |
- otherwise it's a body |
| 359 |
""" |
| 360 |
if isinstance(result, HttpResponseBase): |
| 361 |
return result |
| 362 |
|
| 363 |
status: int = 200 |
| 364 |
if len(self.response_models) == 1: |
| 365 |
status = next(iter(self.response_models)) |
| 366 |
|
| 367 |
if isinstance(result, Status): |
| 368 |
status = result.status_code |
| 369 |
result = result.value |
| 370 |
elif isinstance(result, tuple) and len(result) == 2: |
| 371 |
warnings.warn( |
| 372 |
"Returning tuple (status_code, response) is deprecated. " |
| 373 |
"Use Status(status_code, response) instead.", |
| 374 |
DeprecationWarning, |
| 375 |
stacklevel=2, |
| 376 |
) |
| 377 |
status, result = result |
| 378 |
|
| 379 |
if status in self.response_models: |
| 380 |
response_model = self.response_models[status] |
| 381 |
elif Ellipsis in self.response_models: |
| 382 |
response_model = self.response_models[Ellipsis] |
| 383 |
else: |
| 384 |
raise ConfigError( |
| 385 |
f"Schema for status {status} is not set in response" |
| 386 |
f" {self.response_models.keys()}" |
| 387 |
) |
| 388 |
|
| 389 |
temporal_response.status_code = status |
| 390 |
|
| 391 |
if response_model is NOT_SET: |
| 392 |
return self.api.create_response( |
| 393 |
request, result, temporal_response=temporal_response |
| 394 |
) |
| 395 |
|
| 396 |
if response_model is None: |
| 397 |
|
| 398 |
return temporal_response |
| 399 |
|
| 400 |
model_dump_kwargs = self._model_dump_kwargs(request, status) |
| 401 |
|
| 402 |
|
| 403 |
resp_annotation = response_model.model_fields["response"].annotation |
| 404 |
if ( |
| 405 |
isinstance(resp_annotation, type) |
| 406 |
and isinstance(result, BaseModel) |
| 407 |
and isinstance(result, resp_annotation) |
| 408 |
): |
| 409 |
result = cast(BaseModel, result).model_dump( |
| 410 |
by_alias=self.by_alias, |
| 411 |
exclude_unset=self.exclude_unset, |
| 412 |
exclude_defaults=self.exclude_defaults, |
| 413 |
exclude_none=self.exclude_none, |
| 414 |
**model_dump_kwargs, |
| 415 |
) |
| 416 |
return self.api.create_response( |
| 417 |
request, result, temporal_response=temporal_response |
| 418 |
) |
| 419 |
|
| 420 |
resp_object = ResponseObject(result) |
| 421 |
|
| 422 |
validated_object = response_model.model_validate( |
| 423 |
resp_object, context={"request": request, "response_status": status} |
| 424 |
) |
| 425 |
|
| 426 |
result = validated_object.model_dump( |
| 427 |
by_alias=self.by_alias, |
| 428 |
exclude_unset=self.exclude_unset, |
| 429 |
exclude_defaults=self.exclude_defaults, |
| 430 |
exclude_none=self.exclude_none, |
| 431 |
**model_dump_kwargs, |
| 432 |
)["response"] |
| 433 |
return self.api.create_response( |
| 434 |
request, result, temporal_response=temporal_response |
| 435 |
) |
| 436 |
|
| 437 |
def _get_values( |
| 438 |
self, request: HttpRequest, path_params: Any, temporal_response: HttpResponse |
| 439 |
) -> DictStrAny: |
| 440 |
values = {} |
| 441 |
error_contexts: List[ValidationErrorContext] = [] |
| 442 |
for model in self.models: |
| 443 |
try: |
| 444 |
data = model.resolve(request, self.api, path_params) |
| 445 |
values.update(data) |
| 446 |
except pydantic.ValidationError as e: |
| 447 |
error_contexts.append( |
| 448 |
ValidationErrorContext(pydantic_validation_error=e, model=model) |
| 449 |
) |
| 450 |
if error_contexts: |
| 451 |
validation_error = self.api.validation_error_from_error_contexts( |
| 452 |
error_contexts |
| 453 |
) |
| 454 |
raise validation_error |
| 455 |
if self.signature.response_arg: |
| 456 |
values[self.signature.response_arg] = temporal_response |
| 457 |
return values |
| 458 |
|
| 459 |
def _create_response_model_multiple( |
| 460 |
self, response_param: DictStrAny |
| 461 |
) -> Dict[str, Optional[Type[Schema]]]: |
| 462 |
result = {} |
| 463 |
for key, model in response_param.items(): |
| 464 |
status_codes = isinstance(key, Iterable) and key or [key] |
| 465 |
for code in status_codes: |
| 466 |
result[code] = self._create_response_model(model) |
| 467 |
return result |
| 468 |
|
| 469 |
def _create_response_model(self, response_param: Any) -> Optional[Type[Schema]]: |
| 470 |
if response_param is None: |
| 471 |
return None |
| 472 |
attrs = {"__annotations__": {"response": response_param}} |
| 473 |
return type("NinjaResponseSchema", (Schema,), attrs) |
| 474 |
|
| 475 |
|
| 476 |
class AsyncOperation(Operation): |
| 477 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 478 |
super().__init__(*args, **kwargs) |
| 479 |
self.is_async = True |
| 480 |
|
| 481 |
async def run(self, request: HttpRequest, **kw: Any) -> HttpResponseBase: |
| 482 |
error = await self._run_checks(request) |
| 483 |
if error: |
| 484 |
return error |
| 485 |
try: |
| 486 |
temporal_response = self.api.create_temporal_response(request) |
| 487 |
values = self._get_values(request, kw, temporal_response) |
| 488 |
if self.stream_format: |
| 489 |
result = self.view_func(request, **values) |
| 490 |
return await self._async_stream_response( |
| 491 |
request, result, temporal_response |
| 492 |
) |
| 493 |
result = await self.view_func(request, **values) |
| 494 |
return self._result_to_response(request, result, temporal_response) |
| 495 |
except Exception as e: |
| 496 |
return self.api.on_exception(request, e) |
| 497 |
|
| 498 |
async def _async_stream_response( |
| 499 |
self, |
| 500 |
request: HttpRequest, |
| 501 |
generator: Any, |
| 502 |
temporal_response: HttpResponse, |
| 503 |
) -> StreamingHttpResponse: |
| 504 |
"""Create a StreamingHttpResponse from an async generator.""" |
| 505 |
assert self.stream_format is not None |
| 506 |
fmt = self.stream_format |
| 507 |
|
| 508 |
async def content_gen() -> Any: |
| 509 |
async for item in generator: |
| 510 |
data = self._validate_stream_item(item, request) |
| 511 |
yield fmt.format_chunk(data) |
| 512 |
|
| 513 |
return await create_streaming_response( |
| 514 |
content_gen(), |
| 515 |
content_type=fmt.media_type, |
| 516 |
status=temporal_response.status_code, |
| 517 |
temporal_response=temporal_response, |
| 518 |
extra_headers=fmt.response_headers(), |
| 519 |
) |
| 520 |
|
| 521 |
async def _run_checks(self, request: HttpRequest) -> Optional[HttpResponse]: |
| 522 |
"Runs security/throttle checks for each operation" |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
if self.csrf_exempt: |
| 527 |
request._ninja_csrf_exempt = True |
| 528 |
|
| 529 |
|
| 530 |
if self.auth_callbacks: |
| 531 |
error = await self._run_authentication(request) |
| 532 |
if error: |
| 533 |
return error |
| 534 |
|
| 535 |
|
| 536 |
if self.throttle_objects: |
| 537 |
error = self._check_throttles(request) |
| 538 |
if error: |
| 539 |
return error |
| 540 |
|
| 541 |
return None |
| 542 |
|
| 543 |
async def _run_authentication(self, request: HttpRequest) -> Optional[HttpResponse]: |
| 544 |
for callback in self.auth_callbacks: |
| 545 |
try: |
| 546 |
if is_async_callable(callback) or getattr(callback, "is_async", False): |
| 547 |
cor: Optional[Coroutine] = callback(request) |
| 548 |
if cor is None: |
| 549 |
result = None |
| 550 |
else: |
| 551 |
result = await cor |
| 552 |
else: |
| 553 |
result = await sync_to_async(callback)(request) |
| 554 |
except Exception as exc: |
| 555 |
return self.api.on_exception(request, exc) |
| 556 |
|
| 557 |
if result: |
| 558 |
request.auth = result |
| 559 |
return None |
| 560 |
return self.api.on_exception(request, AuthenticationError()) |
| 561 |
|
| 562 |
|
| 563 |
class PathView: |
| 564 |
def __init__(self) -> None: |
| 565 |
self.operations: List[Operation] = [] |
| 566 |
self.is_async = False |
| 567 |
self.url_name: Optional[str] = None |
| 568 |
|
| 569 |
def add_operation( |
| 570 |
self, |
| 571 |
path: str, |
| 572 |
methods: List[str], |
| 573 |
view_func: Callable, |
| 574 |
*, |
| 575 |
auth: Optional[Union[Sequence[Callable], Callable, NOT_SET_TYPE]] = NOT_SET, |
| 576 |
throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET, |
| 577 |
response: Any = NOT_SET, |
| 578 |
operation_id: Optional[str] = None, |
| 579 |
summary: Optional[str] = None, |
| 580 |
description: Optional[str] = None, |
| 581 |
tags: Optional[List[str]] = None, |
| 582 |
deprecated: Optional[bool] = None, |
| 583 |
by_alias: Optional[bool] = None, |
| 584 |
exclude_unset: Optional[bool] = None, |
| 585 |
exclude_defaults: Optional[bool] = None, |
| 586 |
exclude_none: Optional[bool] = None, |
| 587 |
url_name: Optional[str] = None, |
| 588 |
include_in_schema: bool = True, |
| 589 |
openapi_extra: Optional[Dict[str, Any]] = None, |
| 590 |
) -> Operation: |
| 591 |
if url_name: |
| 592 |
self.url_name = url_name |
| 593 |
|
| 594 |
OperationClass = Operation |
| 595 |
is_streaming = isinstance(response, _StreamAlias) |
| 596 |
if is_async(view_func) or ( |
| 597 |
is_streaming and inspect.isasyncgenfunction(view_func) |
| 598 |
): |
| 599 |
self.is_async = True |
| 600 |
OperationClass = AsyncOperation |
| 601 |
|
| 602 |
operation = OperationClass( |
| 603 |
path, |
| 604 |
methods, |
| 605 |
view_func, |
| 606 |
auth=auth, |
| 607 |
throttle=throttle, |
| 608 |
response=response, |
| 609 |
operation_id=operation_id, |
| 610 |
summary=summary, |
| 611 |
description=description, |
| 612 |
tags=tags, |
| 613 |
deprecated=deprecated, |
| 614 |
by_alias=by_alias, |
| 615 |
exclude_unset=exclude_unset, |
| 616 |
exclude_defaults=exclude_defaults, |
| 617 |
exclude_none=exclude_none, |
| 618 |
include_in_schema=include_in_schema, |
| 619 |
url_name=url_name, |
| 620 |
openapi_extra=openapi_extra, |
| 621 |
) |
| 622 |
|
| 623 |
self.operations.append(operation) |
| 624 |
view_func._ninja_operation = operation |
| 625 |
|
| 626 |
return operation |
| 627 |
|
| 628 |
def clone(self) -> "PathView": |
| 629 |
""" |
| 630 |
Create a fresh copy of this PathView with cloned operations. |
| 631 |
|
| 632 |
This method is used when mounting the same router multiple times |
| 633 |
to ensure each mount has independent PathView and Operation instances. |
| 634 |
""" |
| 635 |
cloned = PathView() |
| 636 |
cloned.is_async = self.is_async |
| 637 |
cloned.url_name = self.url_name |
| 638 |
cloned.operations = [op.clone() for op in self.operations] |
| 639 |
return cloned |
| 640 |
|
| 641 |
def get_view(self) -> Callable: |
| 642 |
|
| 643 |
|
| 644 |
if self.is_async: |
| 645 |
|
| 646 |
async def async_view_wrapper( |
| 647 |
request: HttpRequest, *args: Any, **kwargs: Any |
| 648 |
) -> HttpResponseBase: |
| 649 |
return await self._async_view(request, *args, **kwargs) |
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
async_view_wrapper.csrf_exempt = True |
| 654 |
|
| 655 |
return async_view_wrapper |
| 656 |
else: |
| 657 |
|
| 658 |
def sync_view_wrapper( |
| 659 |
request: HttpRequest, *args: Any, **kwargs: Any |
| 660 |
) -> HttpResponseBase: |
| 661 |
return self._sync_view(request, *args, **kwargs) |
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
sync_view_wrapper.csrf_exempt = True |
| 666 |
|
| 667 |
return sync_view_wrapper |
| 668 |
|
| 669 |
def _sync_view(self, request: HttpRequest, *a: Any, **kw: Any) -> HttpResponseBase: |
| 670 |
operation = self._find_operation(request) |
| 671 |
if operation is None: |
| 672 |
return self._not_allowed() |
| 673 |
return operation.run(request, *a, **kw) |
| 674 |
|
| 675 |
async def _async_view( |
| 676 |
self, request: HttpRequest, *a: Any, **kw: Any |
| 677 |
) -> HttpResponseBase: |
| 678 |
operation = self._find_operation(request) |
| 679 |
if operation is None: |
| 680 |
return self._not_allowed() |
| 681 |
if operation.is_async: |
| 682 |
return await cast(AsyncOperation, operation).run(request, *a, **kw) |
| 683 |
return await sync_to_async(operation.run)(request, *a, **kw) |
| 684 |
|
| 685 |
def _find_operation(self, request: HttpRequest) -> Optional[Operation]: |
| 686 |
for op in self.operations: |
| 687 |
if request.method in op.methods: |
| 688 |
return op |
| 689 |
return None |
| 690 |
|
| 691 |
def _not_allowed(self) -> HttpResponse: |
| 692 |
allowed_methods = set() |
| 693 |
for op in self.operations: |
| 694 |
allowed_methods.update(op.methods) |
| 695 |
return HttpResponseNotAllowed(allowed_methods, content=b"Method not allowed") |
| 696 |
|
| 697 |
|
| 698 |
class ResponseObject: |
| 699 |
"Basically this is just a helper to be able to pass response to pydantic's model_validate" |
| 700 |
|
| 701 |
def __init__(self, response: HttpResponse) -> None: |
| 702 |
self.response = response |