Debian Codegraph @

ninja/openapi/docs.py

raw symbols SCIP
1 import json
2 from abc import ABC, abstractmethod
3 from pathlib import Path
4 from typing import TYPE_CHECKING, Any, Optional
5
6 from django.conf import settings
7 from django.http import HttpRequest, HttpResponse
8 from django.shortcuts import render
9 from django.urls import reverse
10
11 from ninja.constants import NOT_SET
12 from ninja.types import DictStrAny
13
14 if TYPE_CHECKING:
15 # if anyone knows a cleaner way to make mypy happy - welcome
16 from ninja import NinjaAPI # pragma: no cover
17
18 ABS_TPL_PATH = Path(__file__).parent.parent / "templates/ninja/"
19
20
21 class DocsBase(ABC):
22 @abstractmethod
23 def render_page(
24 self, request: HttpRequest, api: "NinjaAPI", **kwargs: Any
25 ) -> HttpResponse:
26 pass # pragma: no cover
27
28 def get_openapi_url(self, api: "NinjaAPI", path_params: DictStrAny) -> str:
29 return reverse(f"{api.urls_namespace}:openapi-json", kwargs=path_params)
30
31
32 class Swagger(DocsBase):
33 template = "ninja/swagger.html"
34 template_cdn = str(ABS_TPL_PATH / "swagger_cdn.html")
35 default_settings = {
36 "layout": "BaseLayout",
37 "deepLinking": True,
38 }
39
40 def __init__(self, settings: Optional[DictStrAny] = None):
41 self.settings = {}
42 self.settings.update(self.default_settings)
43 if settings:
44 self.settings.update(settings)
45
46 def render_page(
47 self, request: HttpRequest, api: "NinjaAPI", **kwargs: Any
48 ) -> HttpResponse:
49 self.settings["url"] = self.get_openapi_url(api, kwargs)
50 context = {
51 "swagger_settings": json.dumps(self.settings, indent=1),
52 "api": api,
53 "add_csrf": _csrf_needed(api),
54 }
55 return render_template(request, self.template, self.template_cdn, context)
56
57
58 class Redoc(DocsBase):
59 template = "ninja/redoc.html"
60 template_cdn = str(ABS_TPL_PATH / "redoc_cdn.html")
61 default_settings: DictStrAny = {}
62
63 def __init__(self, settings: Optional[DictStrAny] = None):
64 self.settings = {}
65 self.settings.update(self.default_settings)
66 if settings:
67 self.settings.update(settings)
68
69 def render_page(
70 self, request: HttpRequest, api: "NinjaAPI", **kwargs: Any
71 ) -> HttpResponse:
72 context = {
73 "redoc_settings": json.dumps(self.settings, indent=1),
74 "openapi_json_url": self.get_openapi_url(api, kwargs),
75 "api": api,
76 }
77 return render_template(request, self.template, self.template_cdn, context)
78
79
80 def render_template(
81 request: HttpRequest, template: str, template_cdn: str, context: DictStrAny
82 ) -> HttpResponse:
83 """
84 I do not really want ninja to be required in INSTALLED_APPS to ease installation
85 so it automatically detects - if ninja is in INSTALLED_APPS - then we render with django.shortcuts.render
86 otherwise - rendering custom html with swagger js from cdn
87 """
88 if "ninja" in settings.INSTALLED_APPS:
89 return render(request, template, context)
90 else:
91 return _render_cdn_template(request, template_cdn, context)
92
93
94 def _render_cdn_template(
95 request: HttpRequest, template_path: str, context: Optional[DictStrAny] = None
96 ) -> HttpResponse:
97 "this is helper to find and render html template when ninja is not in INSTALLED_APPS"
98 from django.template import RequestContext, Template
99
100 tpl = Template(Path(template_path).read_text())
101 html = tpl.render(RequestContext(request, context))
102 return HttpResponse(html)
103
104
105 def _csrf_needed(api: "NinjaAPI") -> bool:
106 """
107 Check if any of the API's auth handlers require CSRF protection.
108 """
109 if not api.auth or api.auth == NOT_SET:
110 return False
111
112 return any(getattr(a, "csrf", False) for a in api.auth) # type: ignore