Debian Codegraph @

docs/examples/openapi/plugins/custom_plugin.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Sequence
4 from typing import Any
5
6 from litestar.connection import Request
7 from litestar.openapi.plugins import OpenAPIRenderPlugin
8
9
10 class ScalarRenderPlugin(OpenAPIRenderPlugin):
11 def __init__(
12 self,
13 *,
14 version: str = "1.19.5",
15 js_url: str | None = None,
16 css_url: str | None = None,
17 path: str | Sequence[str] = "/scalar",
18 **kwargs: Any,
19 ) -> None:
20 self.js_url = js_url or f"https://cdn.jsdelivr.net/npm/@scalar/api-reference@{version}"
21 self.css_url = css_url
22 super().__init__(path=path, **kwargs)
23
24 def render(self, request: Request, openapi_schema: dict[str, Any]) -> bytes:
25 style_sheet_link = f'<link rel="stylesheet" type="text/css" href="{self.css_url}">' if self.css_url else ""
26 head = f"""
27 <head>
28 <title>{openapi_schema["info"]["title"]}</title>
29 {self.style}
30 <meta charset="utf-8"/>
31 <meta name="viewport" content="width=device-width, initial-scale=1">
32 {self.favicon}
33 {style_sheet_link}
34 </head>
35 """
36
37 body = f"""
38 <script
39 id="api-reference"
40 data-url="openapi.json">
41 </script>
42 <script src="{self.js_url}" crossorigin></script>
43 """
44
45 return f"""
46 <!DOCTYPE html>
47 <html>
48 {head}
49 {body}
50 </html>
51 """.encode()