| 1 |
from functools import partial |
| 2 |
from typing import Any, Callable, Tuple |
| 3 |
|
| 4 |
from typing_extensions import Literal |
| 5 |
|
| 6 |
from ninja.operation import Operation |
| 7 |
from ninja.types import TCallable |
| 8 |
from ninja.utils import contribute_operation_callback |
| 9 |
|
| 10 |
|
| 11 |
DecoratorMode = Literal["operation", "view"] |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
def decorate_view(*decorators: Callable[..., Any]) -> Callable[[TCallable], TCallable]: |
| 28 |
def outer_wrapper(op_func: TCallable) -> TCallable: |
| 29 |
if hasattr(op_func, "_ninja_operation"): |
| 30 |
|
| 31 |
_apply_decorators(decorators, op_func._ninja_operation) |
| 32 |
else: |
| 33 |
|
| 34 |
contribute_operation_callback( |
| 35 |
op_func, partial(_apply_decorators, decorators) |
| 36 |
) |
| 37 |
|
| 38 |
return op_func |
| 39 |
|
| 40 |
return outer_wrapper |
| 41 |
|
| 42 |
|
| 43 |
def _apply_decorators( |
| 44 |
decorators: Tuple[Callable[..., Any]], operation: Operation |
| 45 |
) -> None: |
| 46 |
|
| 47 |
if not hasattr(operation, "_run_decorators"): |
| 48 |
operation._run_decorators = [] |
| 49 |
for deco in decorators: |
| 50 |
operation.run = deco(operation.run) |
| 51 |
operation._run_decorators.append(deco) |