68 lines
2.0 KiB
Python
68 lines
2.0 KiB
Python
"""把现站机构备案整栏一次性写入机构名录。
|
|
|
|
样例已保存在本命令旁的 fixtures 中。重复执行按标题更新同一条,不新增重复标题。
|
|
口令只从环境变量读取。测试不访问现站。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import gzip
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app.db import Base, SessionLocal, get_engine
|
|
from app.models.home import HomeArticle, create_article, ensure_article_body_capacity, update_article
|
|
|
|
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "institution_directories.json.gz"
|
|
CATEGORY = "institution_directories"
|
|
|
|
|
|
def load_fixture(path: Path | None = None) -> list[dict]:
|
|
payload = gzip.decompress((path or FIXTURE).read_bytes())
|
|
raw = json.loads(payload.decode("utf-8"))
|
|
if not isinstance(raw, list) or len(raw) != 16:
|
|
raise ValueError("机构名录样例必须是 16 条")
|
|
return raw
|
|
|
|
|
|
def import_institution_directories(db, items: list[dict] | None = None) -> None:
|
|
records = items if items is not None else load_fixture()
|
|
for record in records:
|
|
title = record["title"]
|
|
payload = {
|
|
"category": CATEGORY,
|
|
"title": title,
|
|
"publishedAt": record["publishedAt"],
|
|
"published": True,
|
|
"bodyHtml": record["bodyHtml"],
|
|
"attachmentFileIds": [],
|
|
}
|
|
existing = db.scalar(
|
|
select(HomeArticle.id).where(
|
|
HomeArticle.category == CATEGORY,
|
|
HomeArticle.title == title,
|
|
)
|
|
)
|
|
if existing is None:
|
|
create_article(db, payload)
|
|
else:
|
|
update_article(db, existing, payload)
|
|
|
|
|
|
def main() -> None:
|
|
engine = get_engine()
|
|
Base.metadata.create_all(bind=engine)
|
|
SessionLocal.configure(bind=engine)
|
|
db = SessionLocal()
|
|
try:
|
|
ensure_article_body_capacity(db)
|
|
import_institution_directories(db)
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|