Debian Codegraph @

ninja/decorators.py

raw symbols SCIP
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 # Type for decorator modes
11 DecoratorMode = Literal["operation", "view"]
12
13 # Since @api.method decorator is applied to function
14 # that is not always returns a HttpResponse object
15 # there is no way to apply some standard decorators form
16 # django stdlib or public plugins
17 #
18 # @decorate_view allows to apply any view decorator to Ninja api operation
19 #
20 # @api.get("/some")
21 # @decorate_view(cache_page(60 * 15)) # <-------
22 # def some(request):
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 # Means user used decorate_view on top of @api.method
31 _apply_decorators(decorators, op_func._ninja_operation) # type: ignore
32 else:
33 # Means user used decorate_view after(bottom) of @api.method
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 # Track decorators for cloning support
47 if not hasattr(operation, "_run_decorators"):
48 operation._run_decorators = [] # type: ignore
49 for deco in decorators:
50 operation.run = deco(operation.run) # type: ignore
51 operation._run_decorators.append(deco) # type: ignore