"""Renders the OpenAPI schema into a self-contained HTML reference.
Swagger UI and ReDoc pull their JavaScript from a CDN, which is not always
reachable — closed corporate networks, proxies that require authentication,
servers without internet access. In that case ``/api/docs/`` would be blank,
so the same schema is rendered server-side into a page with inline CSS and no
external requests.
The renderer is used by two entry points:
* ``GET /api/docs/`` — always available reference;
* ``manage.py export_api_docs`` — writes the same page into a file.
"""
import html
import json
from django.http import HttpResponse
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; --accent:#1c4fd8; }
* { 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 20px; }
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; }
.toolbar { position:sticky; top:0; z-index:5; background:rgba(247,249,251,.96);
backdrop-filter:blur(6px); border-bottom:1px solid var(--line);
padding:12px 32px; display:flex; gap:16px; align-items:center; flex-wrap:wrap; }
.toolbar input { flex:1 1 280px; min-width:220px; padding:9px 12px; font-size:14px;
border:1px solid var(--line); border-radius:8px; background:#fff; }
.toolbar input:focus { outline:2px solid #c7d7f7; border-color:var(--accent); }
.toolbar .count { color:var(--muted); font-size:13px; white-space:nowrap; }
.toolbar a { color:var(--accent); text-decoration:none; font-size:13px; white-space:nowrap; }
main { padding:22px 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:var(--accent); 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 > .head:hover { background:#f9fbfd; }
.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; word-break:break-all; }
.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; margin-bottom:8px; }
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, footer 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-right:6px; }
.empty { color:var(--muted); font-size:15px; }
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');
});
});
function filterDocs() {
var query = (document.getElementById('q').value || '').toLowerCase().trim();
var shown = 0;
document.querySelectorAll('section.tag').forEach(function (section) {
var visible = 0;
section.querySelectorAll('.op').forEach(function (op) {
var hit = !query || op.textContent.toLowerCase().indexOf(query) !== -1;
op.style.display = hit ? '' : 'none';
if (hit) { visible += 1; }
});
section.style.display = visible ? '' : 'none';
shown += visible;
});
document.getElementById('found').textContent = query
? 'Найдено: ' + shown
: 'Всего методов: ' + document.querySelectorAll('.op').length;
document.getElementById('empty').style.display = shown ? 'none' : '';
}
document.getElementById('q').addEventListener('input', filterDocs);
filterDocs();
"""
def esc(value) -> str:
return html.escape(str(value), quote=False)
def render_rich(text: str) -> str:
"""Very small subset of markdown: **bold** and `code`."""
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) def build_schema() -> dict: """Returns the OpenAPI schema for the public API.""" generator = SchemaGenerator() return generator.get_schema(request=None, public=True) def render_api_docs_html(schema: dict | None = None) -> str: """Renders the schema into a standalone HTML page.""" schema = schema if schema is not None else build_schema() 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", ""))}