unis-oa/backend/scripts/apply_portal_covers.py

64 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""Attach the bundled cover images to the seeded portal articles.
Fresh databases get covers straight from ``app/seed.py``. Run this once against an
already-seeded database so the headline carousel on the home page is not text only:
python3 scripts/apply_portal_covers.py [--force]
``--force`` also replaces covers that were set by hand.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
from sqlalchemy import select # noqa: E402
from app import models # noqa: E402
from app.db import SessionLocal # noqa: E402
from app.seed import PORTAL_COVER_ASSETS, PORTAL_DOCUMENTS, stage_cover # noqa: E402
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--force", action="store_true", help="replace covers that are already set")
args = parser.parse_args()
assets = PORTAL_COVER_ASSETS
wanted = {spec["title"]: str(spec.get("cover") or "") for spec in PORTAL_DOCUMENTS if spec.get("cover")}
if not wanted:
print("没有配置封面,直接退出")
return 0
done: list[str] = []
skipped: list[str] = []
with SessionLocal() as db:
rows = db.execute(select(models.CmsDocument).where(models.CmsDocument.title.in_(list(wanted)))).scalars().all()
for row in rows:
name = wanted.get(row.title, "")
source = assets / name
if not name or not source.is_file():
skipped.append(f"{row.title}(缺少素材 {name})")
continue
if row.cover and not args.force:
skipped.append(f"{row.title}(已有封面 {row.cover})")
continue
row.cover = stage_cover(name)
done.append(f"{row.title} -> {name}")
db.commit()
for line in done:
print("[ok] ", line)
for line in skipped:
print("[skip]", line)
print(f"共更新 {len(done)} 篇,跳过 {len(skipped)} 篇")
return 0
if __name__ == "__main__":
sys.exit(main())