50 lines
2.8 KiB
Python
50 lines
2.8 KiB
Python
|
|
"""Static operation and schema index for the Chinese API manual."""
|
|||
|
|
from html import escape
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
|
|||
|
|
def schema_link(schema):
|
|||
|
|
if "$ref" in schema:
|
|||
|
|
name = schema["$ref"].rsplit("/", 1)[-1]
|
|||
|
|
return f'<a href="#schema-{escape(name)}">{escape(name)}</a>'
|
|||
|
|
if "anyOf" in schema or "oneOf" in schema:
|
|||
|
|
return " / ".join(schema_link(item) for item in schema.get("anyOf", schema.get("oneOf", [])))
|
|||
|
|
if schema.get("type") == "array":
|
|||
|
|
return f'array<{schema_link(schema.get("items", {}))}>'
|
|||
|
|
return escape(schema.get("type", "未声明固定结构"))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def operation_index(contract):
|
|||
|
|
schemas = contract["components"]["schemas"]
|
|||
|
|
operations = []
|
|||
|
|
for path, methods in contract["paths"].items():
|
|||
|
|
for method, op in methods.items():
|
|||
|
|
if method not in {"get", "post", "put", "patch", "delete", "head", "options"}:
|
|||
|
|
continue
|
|||
|
|
fields = []
|
|||
|
|
for p in op.get("parameters", []):
|
|||
|
|
required = "必填" if p.get("required") else "可选"
|
|||
|
|
fields.append(f'{escape(p["in"])} · <code>{escape(p["name"])}</code> · '
|
|||
|
|
f'{schema_link(p["schema"])} · {required}')
|
|||
|
|
body = op.get("requestBody", {})
|
|||
|
|
for mime, item in body.get("content", {}).items():
|
|||
|
|
fields.append(f'body · {escape(mime)} · {schema_link(item.get("schema", {}))}')
|
|||
|
|
for status, response in op["responses"].items():
|
|||
|
|
types = [f'{escape(mime)} · {schema_link(item.get("schema", {}))}'
|
|||
|
|
for mime, item in response.get("content", {}).items()]
|
|||
|
|
fields.append(f'HTTP {escape(status)} · {", ".join(types) or escape(response["description"])}')
|
|||
|
|
operations.append(f'<details><summary><code>{method.upper()} {escape(path)}</code></summary>'
|
|||
|
|
f'<ul>{"".join(f"<li>{f}</li>" for f in fields)}</ul></details>')
|
|||
|
|
models = []
|
|||
|
|
for name, data in sorted(schemas.items()):
|
|||
|
|
formal = escape(json.dumps(data, indent=2, ensure_ascii=False))
|
|||
|
|
models.append(f'<details id="schema-{escape(name)}"><summary><code>{escape(name)}</code></summary>'
|
|||
|
|
f'<pre><code>{formal}</code></pre></details>')
|
|||
|
|
return (f'<h2 id="route-index">接口索引({len(operations)} 项)</h2>'
|
|||
|
|
'<p>点击方法与路径查看 OpenAPI 声明。会话、CSRF、手动读取的请求头和动态响应见上文。'
|
|||
|
|
'媒体下载、SSE、SRT 的实际响应类型也以上文说明为准。</p>'
|
|||
|
|
+ "".join(operations)
|
|||
|
|
+ '<h2 id="body-schemas">请求体与字段定义</h2>'
|
|||
|
|
+ '<p>点击模型名可展开完整定义。required 列出必填字段,properties 描述类型、格式和取值。</p>'
|
|||
|
|
+ "".join(models))
|