54 lines
2.0 KiB
Python
54 lines
2.0 KiB
Python
"""
|
|
修复 home_modules[news].content.posts 里的旧 post 快照:
|
|
- 按 title 匹配新的 articles 表
|
|
- 更新 id 和 slug 为新表中的值
|
|
- 同步 cover_image / summary(以新表为准)
|
|
"""
|
|
import json
|
|
from sqlalchemy import create_engine, text
|
|
|
|
engine = create_engine('sqlite:///cms.db')
|
|
with engine.connect() as conn:
|
|
# 读取 news 模块的 content
|
|
row = conn.execute(text("SELECT id, content FROM home_modules WHERE code='news' LIMIT 1")).fetchone()
|
|
if not row:
|
|
print("未找到 news 模块,跳过")
|
|
raise SystemExit(0)
|
|
|
|
mod_id, content_str = row
|
|
content = json.loads(content_str) if content_str else {}
|
|
posts = content.get('posts', [])
|
|
print(f"home_modules[news].posts 共 {len(posts)} 条快照")
|
|
|
|
updated = 0
|
|
for idx, post in enumerate(posts):
|
|
if not post:
|
|
continue
|
|
title = post.get('title')
|
|
if not title:
|
|
continue
|
|
art = conn.execute(
|
|
text("SELECT id, title, slug, summary, cover_image FROM articles WHERE title = :t LIMIT 1"),
|
|
{"t": title}
|
|
).fetchone()
|
|
if art:
|
|
old_slug = post.get('slug')
|
|
post['id'] = art[0]
|
|
post['slug'] = art[2]
|
|
post['summary'] = art[3] or post.get('summary', '')
|
|
post['cover_image'] = art[4] or post.get('cover_image', '')
|
|
updated += 1
|
|
print(f" [{idx}] {title[:40]}... | 老 slug={old_slug} -> 新 slug={art[2]}")
|
|
else:
|
|
print(f" [{idx}] {title[:40]}... | 找不到对应的新 article(已清空此快照位)")
|
|
posts[idx] = None # 置空该位
|
|
|
|
content['posts'] = posts
|
|
new_content_str = json.dumps(content, ensure_ascii=False)
|
|
conn.execute(
|
|
text("UPDATE home_modules SET content = :c WHERE id = :id"),
|
|
{"c": new_content_str, "id": mod_id}
|
|
)
|
|
conn.commit()
|
|
print(f"\n更新完成:成功映射 {updated} 条;写入 home_modules.id={mod_id}")
|