Debian Codegraph @

ninja/utils.py

raw symbols SCIP
1 import inspect
2 from typing import Any, Callable, Optional, Type
3
4 from django.http import HttpRequest, HttpResponseForbidden
5 from django.middleware.csrf import CsrfViewMiddleware
6
7 __all__ = [
8 "check_csrf",
9 "normalize_path",
10 "contribute_operation_callback",
11 ]
12
13
14 def replace_path_param_notation(path: str) -> str:
15 return path.replace("{", "<").replace("}", ">")
16
17
18 def normalize_path(path: str) -> str:
19 while "//" in path:
20 path = path.replace("//", "/")
21 return path
22
23
24 def _no_view() -> None:
25 pass # pragma: no cover
26
27
28 def check_csrf(
29 request: HttpRequest, callback: Callable = _no_view
30 ) -> Optional[HttpResponseForbidden]:
31 mware = CsrfViewMiddleware(lambda x: HttpResponseForbidden()) # pragma: no cover
32 request.csrf_processing_done = False # type: ignore
33 mware.process_request(request)
34 return mware.process_view(request, callback, (), {})
35
36
37 def is_async_callable(f: Callable[..., Any]) -> bool:
38 return inspect.iscoroutinefunction(f) or inspect.iscoroutinefunction(
39 getattr(f, "__call__", None)
40 )
41
42
43 def is_optional_type(t: Type[Any]) -> bool:
44 try:
45 return type(None) in t.__args__
46 except AttributeError:
47 return False
48
49
50 def contribute_operation_callback(
51 func: Callable[..., Any], callback: Callable[..., Any]
52 ) -> None:
53 if not hasattr(func, "_ninja_contribute_to_operation"):
54 func._ninja_contribute_to_operation = [] # type: ignore
55 func._ninja_contribute_to_operation.append(callback) # type: ignore
56
57
58 def contribute_operation_args(
59 func: Callable[..., Any], arg_name: str, arg_type: Type, arg_source: Any
60 ) -> None:
61 if not hasattr(func, "_ninja_contribute_args"):
62 func._ninja_contribute_args = [] # type: ignore
63 func._ninja_contribute_args.append((arg_name, arg_type, arg_source)) # type: ignore