"""Exports the OpenAPI schema into a standalone HTML reference.
Swagger UI and ReDoc load their JavaScript from a CDN, which is not always
reachable (closed corporate networks, servers without internet access). This
command renders the same schema into one self-contained HTML file with inline
CSS and no external requests.
"""
import html
import json
from pathlib import Path
from django.core.management.base import BaseCommand
from drf_spectacular.generators import SchemaGenerator
METHOD_COLORS = {
"get": "#0b7a3b",
"post": "#1c4fd8",
"put": "#b26a00",
"patch": "#8a4b00",
"delete": "#b3261e",
}
CSS = """
:root { --fg:#16212b; --muted:#5b6b7a; --line:#e2e8ee; --bg:#f7f9fb; }
* { box-sizing: border-box; }
body { margin:0; font:15px/1.55 -apple-system,"Segoe UI",Roboto,Arial,sans-serif;
color:var(--fg); background:var(--bg); }
header { background:#fff; border-bottom:1px solid var(--line); padding:28px 32px 22px; }
header h1 { margin:0 0 6px; font-size:26px; letter-spacing:-.3px; }
header .version { color:var(--muted); font-size:13px; }
header p { margin:10px 0 0; color:var(--muted); max-width:900px; white-space:pre-wrap; }
main { padding:24px 32px 60px; max-width:1100px; }
nav { background:#fff; border:1px solid var(--line); border-radius:10px;
padding:12px 18px; margin-bottom:26px; }
nav a { display:inline-block; color:#1c4fd8; text-decoration:none;
margin:4px 18px 4px 0; font-size:14px; }
nav a:hover { text-decoration:underline; }
section.tag { margin-bottom:38px; }
section.tag > h2 { font-size:21px; margin:0 0 4px; }
section.tag > .tagdesc { color:var(--muted); margin:0 0 16px; max-width:850px;
white-space:pre-wrap; }
.op { background:#fff; border:1px solid var(--line); border-radius:10px;
margin-bottom:14px; overflow:hidden; }
.op > .head { display:flex; gap:12px; align-items:baseline; padding:14px 18px;
cursor:pointer; }
.op.open > .head { border-bottom:1px solid var(--line); }
.method { font:600 12px/1 ui-monospace,Menlo,Consolas,monospace; color:#fff;
padding:5px 8px; border-radius:5px; text-transform:uppercase; }
.path { font:14px/1.4 ui-monospace,Menlo,Consolas,monospace; }
.summary { color:var(--muted); font-size:14px; margin-left:auto; text-align:right; }
.body { display:none; padding:4px 18px 18px; }
.op.open .body { display:block; }
.desc { color:#31404d; white-space:pre-wrap; margin:12px 0; }
h4 { font-size:13px; text-transform:uppercase; letter-spacing:.5px;
color:var(--muted); margin:18px 0 8px; }
table { border-collapse:collapse; width:100%; font-size:14px; }
th,td { text-align:left; padding:7px 10px; border-bottom:1px solid var(--line);
vertical-align:top; }
th { color:var(--muted); font-weight:600; font-size:12px; text-transform:uppercase; }
td code, p code, li code { background:#eef2f7; padding:1px 5px; border-radius:4px;
font:13px ui-monospace,Menlo,Consolas,monospace; }
.req { color:#b3261e; font-size:12px; }
pre { background:#0f1b26; color:#dde7f0; padding:12px 14px; border-radius:8px;
overflow:auto; font:13px/1.5 ui-monospace,Menlo,Consolas,monospace; }
.badge { display:inline-block; background:#eef2f7; color:#31404d; border-radius:6px;
padding:2px 7px; font-size:12px; margin-left:8px; }
footer { color:var(--muted); font-size:13px; padding:0 32px 40px; }
"""
JS = """
document.querySelectorAll('.op > .head').forEach(function (head) {
head.addEventListener('click', function () {
head.parentElement.classList.toggle('open');
});
});
"""
def esc(value) -> str:
return html.escape(str(value), quote=False)
def render_rich(text: str) -> str:
"""Very small subset of markdown: paragraphs, **bold**, `code`, newlines."""
if not text:
return ""
out = esc(text)
parts = out.split("**")
rebuilt = []
for index, part in enumerate(parts):
rebuilt.append(f"{part}" if index % 2 else part)
out = "".join(rebuilt)
chunks = out.split("`")
rebuilt = []
for index, chunk in enumerate(chunks):
rebuilt.append(f"{chunk}" if index % 2 else chunk)
return "".join(rebuilt)
def resolve(node, schema, depth=0):
"""Resolves $ref against components, with a depth guard."""
if depth > 6 or not isinstance(node, dict):
return node
ref = node.get("$ref")
if not ref:
return node
name = ref.rsplit("/", 1)[-1]
target = schema.get("components", {}).get("schemas", {}).get(name, {})
return resolve(target, schema, depth + 1)
def type_label(prop: dict) -> str:
if "$ref" in prop:
return prop["$ref"].rsplit("/", 1)[-1]
if prop.get("type") == "array":
items = prop.get("items", {})
inner = type_label(items) if items else "object"
return f"array[{inner}]"
if prop.get("enum"):
return "enum (" + ", ".join(str(v) for v in prop["enum"]) + ")"
return prop.get("type", "object")
def fields_table(node, schema, required_names) -> str:
"""Renders object properties as a table. Empty string when not an object."""
node = resolve(node, schema)
props = node.get("properties") if isinstance(node, dict) else None
if not props:
return ""
rows = []
for name, prop in props.items():
prop = resolve(prop, schema) if "$ref" in prop else prop
description = prop.get("description", "")
flag = '*' if name in required_names else ""
rows.append(
f"
{esc(name)}{flag}| Поле | Тип | Описание |
|---|
{esc(label)}
" f"{esc(json.dumps(value, ensure_ascii=False, indent=2))}"
)
return f"{esc(param.get('name', ''))}{flag}| Имя | Где | Тип | " "Описание |
|---|
{esc(code)} {render_rich(description)}
' ) if table: chunks.append(table) chunks.append(examples_block(content, "Пример ответа")) return "".join(chunks) class Command(BaseCommand): help = ( "Рендерит OpenAPI-схему в один автономный HTML-файл " "(без CDN и внешних запросов)." ) def add_arguments(self, parser): parser.add_argument( "--out", default="api-reference.html", help="Куда сохранить HTML (по умолчанию backend/api-reference.html).", ) def handle(self, *args, **options): generator = SchemaGenerator() schema = generator.get_schema(request=None, public=True) info = schema.get("info", {}) declared_tags = schema.get("tags", []) by_tag: dict[str, list] = {} for path, methods in sorted(schema.get("paths", {}).items()): for method, op in methods.items(): for tag in op.get("tags", ["Прочее"]): by_tag.setdefault(tag, []).append((path, method, op)) ordered_tags = [tag["name"] for tag in declared_tags] ordered_tags += [name for name in by_tag if name not in ordered_tags] nav_links = "".join( f'{esc(name)}' for name in ordered_tags ) sections = [] for name in ordered_tags: operations = by_tag.get(name) if not operations: continue description = next( (tag.get("description", "") for tag in declared_tags if tag["name"] == name), "", ) articles = [] for path, method, op in operations: request = request_block(op, schema) responses = responses_block(op, schema) params = parameters_table(op.get("parameters", []), schema) articles.append( '{render_rich(description)}
' + "".join(articles) + "{render_rich(info.get("description", ""))}