Files
homm/backend/apps/common/api_docs.py
T
apuc 3b3e5c429a Serve an offline API reference at /api/docs/
The Swagger UI page was blank on networks where the jsdelivr CDN is
unreachable (here the proxy answers 407), so /api/docs/ now returns a
server-rendered reference built from the same OpenAPI schema: inline
CSS/JS, no external requests, search across methods.

- Extract the renderer into apps/common/api_docs.py
- Add api_docs_view and route it to /api/docs/
- Move Swagger UI to /api/swagger/, keep ReDoc at /api/redoc/
- Let export_api_docs reuse the shared renderer (new search field)
- Update the docs entry points in docs/architecture.md
2026-11-22 22:09:41 +03:00

350 lines
14 KiB
Python

"""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"<strong>{part}</strong>" if index % 2 else part)
out = "".join(rebuilt)
chunks = out.split("`")
rebuilt = []
for index, chunk in enumerate(chunks):
rebuilt.append(f"<code>{chunk}</code>" 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 = '<span class="req">*</span>' if name in required_names else ""
rows.append(
f"<tr><td><code>{esc(name)}</code>{flag}</td>"
f"<td>{esc(type_label(prop))}</td>"
f"<td>{esc(description)}</td></tr>"
)
return (
"<table><tr><th>Поле</th><th>Тип</th><th>Описание</th></tr>"
+ "".join(rows)
+ "</table>"
)
def examples_block(payload, title: str) -> str:
examples = payload.get("examples") if isinstance(payload, dict) else None
if not examples:
return ""
blocks = []
for name, example in examples.items():
value = example.get("value")
label = example.get("summary") or name
blocks.append(
f"<p><strong>{esc(label)}</strong></p>"
f"<pre>{esc(json.dumps(value, ensure_ascii=False, indent=2))}</pre>"
)
return f"<h4>{esc(title)}</h4>" + "".join(blocks)
def parameters_table(parameters, schema) -> str:
if not parameters:
return ""
rows = []
for param in parameters:
param = resolve(param, schema)
meta = param.get("schema", {})
location = param.get("in", "")
flag = '<span class="req">*</span>' if param.get("required") else ""
rows.append(
f"<tr><td><code>{esc(param.get('name', ''))}</code>{flag}</td>"
f"<td>{esc(location)}</td>"
f"<td>{esc(type_label(meta))}</td>"
f"<td>{esc(param.get('description', ''))}</td></tr>"
)
return (
"<h4>Параметры</h4><table><tr><th>Имя</th><th>Где</th><th>Тип</th>"
"<th>Описание</th></tr>" + "".join(rows) + "</table>"
)
def request_block(op, schema) -> str:
body = op.get("requestBody")
if not body:
return ""
body = resolve(body, schema)
content = body.get("content", {}).get("application/json", {})
ref = content.get("schema", {})
required = resolve(ref, schema).get("required", []) if ref else []
table = fields_table(ref, schema, required)
return "<h4>Тело запроса</h4>" + table + examples_block(content, "Примеры запроса")
def responses_block(op, schema) -> str:
chunks = ["<h4>Ответы</h4>"]
for code, response in sorted(op.get("responses", {}).items()):
response = resolve(response, schema)
description = response.get("description", "")
content = response.get("content", {}).get("application/json", {})
ref = content.get("schema", {})
required = resolve(ref, schema).get("required", []) if ref else []
table = fields_table(ref, schema, required) if ref else ""
chunks.append(
f'<p><span class="badge">{esc(code)}</span>{render_rich(description)}</p>'
)
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'<a href="#tag-{esc(name)}">{esc(name)}</a>' 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(
'<article class="op">'
f'<div class="head"><span class="method" '
f'style="background:{METHOD_COLORS.get(method, "#475569")}">'
f"{esc(method)}</span>"
f'<span class="path">{esc(path)}</span>'
f'<span class="summary">{esc(op.get("summary", ""))}</span></div>'
f'<div class="body">'
f'<div class="desc">{render_rich(op.get("description", ""))}</div>'
f"{params}{request}{responses}</div></article>"
)
sections.append(
f'<section class="tag" id="tag-{esc(name)}">'
f"<h2>{esc(name)}</h2>"
f'<p class="tagdesc">{render_rich(description)}</p>'
+ "".join(articles)
+ "</section>"
)
total = sum(len(value) for value in by_tag.values())
return f"""<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{esc(info.get("title", "API"))} — справочник</title>
<style>{CSS}</style>
</head>
<body>
<header>
<h1>{esc(info.get("title", "API"))}</h1>
<div class="version">Версия {esc(info.get("version", ""))}</div>
<p>{render_rich(info.get("description", ""))}</p>
</header>
<div class="toolbar">
<input id="q" type="search" placeholder="Поиск по методу, пути или описанию…"
autocomplete="off" aria-label="Поиск по документации">
<span class="count" id="found">Всего методов: {total}</span>
<a href="/api/schema/" target="_blank" rel="noopener">Схема OpenAPI (YAML)</a>
</div>
<main>
<nav>{nav_links}</nav>
<p class="empty" id="empty" style="display:none">Ничего не найдено.</p>
{''.join(sections)}
</main>
<footer>
Схема сгенерирована из кода приложения и всегда соответствует фактическим
эндпоинтам. Интерактивная версия Swagger UI доступна по адресу
<code>/api/swagger/</code> (требует доступа к CDN).
</footer>
<script>{JS}</script>
</body>
</html>
"""
def api_docs_view(request) -> HttpResponse:
"""Serves the offline API reference."""
return HttpResponse(render_api_docs_html(), content_type="text/html; charset=utf-8")