Coverage for src/lexigram/web/routing/openapi_templates.py: 33%
24 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-25 04:37 +0800
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-25 04:37 +0800
1"""OpenAPI template helpers for Swagger and Redoc UI.
3Provides small wrappers used by `web.routing.openapi.register_openapi_routes` to
4render the `templates/swagger.html` and `templates/redoc.html` templates via
5`Jinja2Templates`.
6"""
8from __future__ import annotations
10import html as _html
11from pathlib import Path
13from lexigram.web.templates.core import Jinja2Templates
15TEMPLATE_DIR = Path(__file__).parent.parent / "templates"
18def _fallback_html(title: str, openapi_url: str, tool_name: str) -> str:
19 """Render a minimal OpenAPI fallback page."""
20 safe_title = _html.escape(title)
21 safe_url = _html.escape(openapi_url)
22 safe_tool = _html.escape(tool_name)
23 return (
24 f"<!DOCTYPE html><html><head><title>{safe_title}</title></head>"
25 f"<body><h1>{safe_title}</h1>"
26 f'<p>OpenAPI JSON: <a href="{safe_url}">{safe_url}</a></p>'
27 f"<p>Install jinja2 to enable the full {safe_tool} UI.</p>"
28 "</body></html>"
29 )
32def get_swagger_ui_html(
33 title: str,
34 openapi_url: str,
35 swagger_js_url: str | None = None,
36 swagger_css_url: str | None = None,
37) -> str:
38 """Render the Swagger UI HTML from template."""
39 try:
40 templates = Jinja2Templates(directory=TEMPLATE_DIR)
41 context = {
42 "title": title,
43 "openapi_url": openapi_url,
44 "swagger_js_url": swagger_js_url,
45 "swagger_css_url": swagger_css_url,
46 }
47 return templates.render_template("swagger.html", context)
48 except ImportError:
49 return _fallback_html(title, openapi_url, "Swagger")
52def get_redoc_html(
53 title: str,
54 openapi_url: str,
55 redoc_js_url: str | None = None,
56) -> str:
57 """Render the ReDoc HTML from template."""
58 try:
59 templates = Jinja2Templates(directory=TEMPLATE_DIR)
60 context = {
61 "title": title,
62 "openapi_url": openapi_url,
63 "redoc_js_url": redoc_js_url,
64 }
65 return templates.render_template("redoc.html", context)
66 except ImportError:
67 return _fallback_html(title, openapi_url, "ReDoc")