Spaces:
Runtime error

backend-bxt / api /content.py
little666fish
add backend
c0be5f0
Raw History Blame Contribute Delete
4.34 kB
"""
@router /api/content
@description 内容管理路由模块
@author wjh
@created at 2025-11-25
"""
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
import os, re, yaml, hashlib, html
from datetime import datetime, timezone
router = APIRouter()
def _backend_root():
return os.path.dirname(os.path.dirname(__file__))
def _content_dir():
return os.path.join(_backend_root(), "content")
def _find_file(slug: str, lang: str):
p = os.path.join(_content_dir(), f"{slug}.{lang}.md")
if os.path.isfile(p):
return p, lang
for name in os.listdir(_content_dir()) if os.path.isdir(_content_dir()) else []:
if name.startswith(f"{slug}.") and name.endswith(".md"):
return os.path.join(_content_dir(), name), name.split(".")[-2]
return None, lang
def _parse_front_matter(text: str):
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
fm = text[3:end+1].strip()
rest = text[end+4:].lstrip()
try:
meta = yaml.safe_load(fm) or {}
except Exception:
meta = {}
return meta, rest
return {}, text
def _inline(s: str):
s = html.escape(s)
s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
s = re.sub(r"\*(.+?)\*", r"<em>\1</em>", s)
s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
s = re.sub(r"\[([^\]]+)\]\((https?://[^\s)]+)\)", r"<a href=\"\2\" rel=\"noopener\" target=\"_blank\">\1</a>", s)
return s
def _md_to_html(md: str):
lines = md.splitlines()
out = []
i = 0
in_ul = False
in_code = False
code_buf = []
while i < len(lines):
line = lines[i]
if line.strip().startswith("```"):
if in_code:
out.append("<pre><code>" + html.escape("\n".join(code_buf)) + "</code></pre>")
code_buf = []
in_code = False
else:
in_code = True
i += 1
continue
if in_code:
code_buf.append(line)
i += 1
continue
if re.match(r"^#{1,6}\s", line):
m = re.match(r"^(#{1,6})\s+(.*)$", line)
level = len(m.group(1))
out.append(f"<h{level}>" + _inline(m.group(2)) + f"</h{level}>")
i += 1
continue
if re.match(r"^\s*-\s+", line):
if not in_ul:
out.append("<ul>")
in_ul = True
item = re.sub(r"^\s*-\s+", "", line)
out.append("<li>" + _inline(item) + "</li>")
i += 1
if i < len(lines) and not re.match(r"^\s*-\s+", lines[i]):
out.append("</ul>")
in_ul = False
continue
if line.strip() == "":
i += 1
continue
out.append("<p>" + _inline(line) + "</p>")
i += 1
if in_ul:
out.append("</ul>")
return "\n".join(out)
@router.get("/{slug}")
async def get_content(slug: str, lang: str = Query("zh-CN")):
path, actual_lang = _find_file(slug, lang)
if not path:
data = {
"slug": slug,
"locale": lang,
"title": "",
"body_html": "<p>暂无内容</p>",
"version": 0,
"updated_at": datetime.now(timezone.utc).isoformat()
}
return JSONResponse({"success": True, "data": data})
with open(path, "r", encoding="utf-8") as f:
text = f.read()
meta, body = _parse_front_matter(text)
title = str(meta.get("title") or "")
if not title:
for l in body.splitlines():
if l.startswith("# "):
title = l[2:].strip()
break
html_body = _md_to_html(body)
version = int(meta.get("version") or int(os.path.getmtime(path)))
updated_at = datetime.fromtimestamp(os.path.getmtime(path), tz=timezone.utc).isoformat()
etag = hashlib.sha256((slug + actual_lang + html_body).encode("utf-8")).hexdigest()
data = {
"slug": slug,
"locale": actual_lang,
"title": title,
"body_html": html_body,
"version": version,
"updated_at": updated_at
}
resp = JSONResponse({"success": True, "data": data})
resp.headers["ETag"] = f'W/"{etag}"'
return resp