Coverage for faststream/specification/asyncapi/site.py: 47%
30 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1from functools import partial
2from http import server
3from typing import TYPE_CHECKING, Any
4from urllib.parse import parse_qs, urlparse
6from faststream._internal._compat import json_dumps
7from faststream._internal.logger import logger
9if TYPE_CHECKING:
10 from faststream.specification import Specification
12ASYNCAPI_JS_DEFAULT_URL = (
13 "https://unpkg.com/@asyncapi/react-component@3.1.5/browser/standalone/index.js"
14)
16ASYNCAPI_CSS_DEFAULT_URL = (
17 "https://unpkg.com/@asyncapi/react-component@3.1.5/styles/default.min.css"
18)
21ASYNCAPI_TRY_IT_PLUGIN_URL = "https://cdn.jsdelivr.net/npm/asyncapi-try-it-plugin@0.3.0-standalone.0/dist/index.iife.min.js"
24def get_asyncapi_html(
25 schema: "Specification",
26 sidebar: bool = True,
27 info: bool = True,
28 servers: bool = True,
29 operations: bool = True,
30 messages: bool = True,
31 schemas: bool = True,
32 errors: bool = True,
33 expand_message_examples: bool = True,
34 asyncapi_js_url: str = ASYNCAPI_JS_DEFAULT_URL,
35 asyncapi_css_url: str = ASYNCAPI_CSS_DEFAULT_URL,
36 try_it_out_plugin_url: str = ASYNCAPI_TRY_IT_PLUGIN_URL,
37 try_it_out_path: str | None = "asyncapi/try",
38) -> str:
39 """Generate HTML for displaying an AsyncAPI document."""
40 config = {
41 "show": {
42 "sidebar": sidebar,
43 "info": info,
44 "servers": servers,
45 "operations": operations,
46 "messages": messages,
47 "schemas": schemas,
48 "errors": errors,
49 },
50 "expand": {
51 "messageExamples": expand_message_examples,
52 },
53 "sidebar": {
54 "showServers": "byDefault",
55 "showOperations": "byDefault",
56 },
57 }
59 if try_it_out_path is not None: 59 ↛ 86line 59 didn't jump to line 86 because the condition on line 59 was always true
60 plugins_js = f"""
61 <script src="{asyncapi_js_url}"></script>
62 <script src="{try_it_out_plugin_url}"></script>
63 <script>
64 const schema = {schema.to_json()};
65 const config = {json_dumps(config).decode()};
66 const endpoint = {try_it_out_path!r};
67 const plugin = window.AsyncApiTryItPlugin.createTryItOutPlugin({{
68 endpointBase: endpoint.replace(/^\\//, ""),
69 resolveEndpoint: () => endpoint,
70 showPayloadSchema: true,
71 showEndpointInput: false,
72 showRealBrokerToggle: true
73 }});
75 window.AsyncApiStandalone.render(
76 {{
77 schema,
78 config,
79 plugins: [plugin]
80 }},
81 document.getElementById("asyncapi")
82 );
83 </script>"""
85 else:
86 standalone_config = {"schema": schema.to_json(), "config": config}
87 plugins_js = f"""
88 <script src="{asyncapi_js_url}"></script>
89 <script>
90 window.AsyncApiStandalone.render(
91 {json_dumps(standalone_config).decode()},
92 document.getElementById("asyncapi")
93 );
94 </script>"""
96 return f"""<!DOCTYPE html>
97<html>
98 <head>
99 <title>{schema.title} AsyncAPI</title>
100 <link rel="icon" href="https://www.asyncapi.com/favicon.ico">
101 <link rel="icon" type="image/png" sizes="16x16" href="https://www.asyncapi.com/favicon-16x16.png">
102 <link rel="icon" type="image/png" sizes="32x32" href="https://www.asyncapi.com/favicon-32x32.png">
103 <link rel="icon" type="image/png" sizes="194x194" href="https://www.asyncapi.com/favicon-194x194.png">
104 <link rel="stylesheet" href="{asyncapi_css_url}">
105 </head>
106 <style>
107 html {{
108 font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;
109 line-height: 1.5;
110 }}
111 </style>
112 <body>
113 <div id="asyncapi"></div>
114 {plugins_js}
115 </body>
116</html>"""
119def serve_app(
120 schema: "Specification",
121 host: str,
122 port: int,
123) -> None:
124 """Serve the HTTPServer with AsyncAPI schema."""
125 logger.info(f"HTTPServer running on http://{host}:{port} (Press CTRL+C to quit)")
126 logger.warning("Please, do not use it in production.")
128 server.HTTPServer(
129 (host, port),
130 partial(_Handler, schema=schema),
131 ).serve_forever()
134class _Handler(server.BaseHTTPRequestHandler):
135 def __init__(
136 self,
137 *args: Any,
138 schema: "Specification",
139 **kwargs: Any,
140 ) -> None:
141 self.schema = schema
142 super().__init__(*args, **kwargs)
144 def get_query_params(self) -> dict[str, bool]:
145 return {
146 i: _str_to_bool(next(iter(j))) if j else False
147 for i, j in parse_qs(urlparse(self.path).query).items()
148 }
150 def do_GET(self) -> None:
151 """Serve a GET request."""
152 query_dict = self.get_query_params()
154 encoding = "utf-8"
155 html = get_asyncapi_html(
156 self.schema,
157 sidebar=query_dict.get("sidebar", True),
158 info=query_dict.get("info", True),
159 servers=query_dict.get("servers", True),
160 operations=query_dict.get("operations", True),
161 messages=query_dict.get("messages", True),
162 schemas=query_dict.get("schemas", True),
163 errors=query_dict.get("errors", True),
164 expand_message_examples=query_dict.get("expandMessageExamples", True),
165 try_it_out_path=None, # CLI serve has no broker — use AsgiFastStream for try-it
166 )
167 body = html.encode(encoding=encoding)
169 self.send_response(200)
170 self.send_header("content-length", str(len(body)))
171 self.send_header("content-type", f"text/html; charset={encoding}")
172 self.end_headers()
173 self.wfile.write(body)
176def _str_to_bool(v: str) -> bool:
177 return v.lower() in {"1", "t", "true", "y", "yes"}