Files
sale/scripts/restore_content_zh.py
T
Hermes fab0aeb22e
Build and Push Docker Image / build-and-push (push) Successful in 1m3s
Build and Push Docker Image / deploy (push) Successful in 10s
feat(i18n): 公告/活动/资讯/分类/轮播改为「中文源 + 日文列」,按语言设置切换
上一版把这几类内容直接翻成日文写进主列,方向错了:它们是运营内容,
要用中文写、后台用中文看,只在语言切成日文时展示日文。

后端
· 模型加并列列(不拆表,量小且改起来不用 join;空值一律回落到中文):
  categories(name_ja, description_ja)
  banners(title_ja, desc_ja, button_ja)
  announcements(title_ja, content_ja)
  articles(title_ja, summary_ja, content_ja)
  lotteries(name_ja, description_ja)、lottery_prizes(name_ja)
· utils/i18n.go:语言解析 ?lang= > X-Lang 头 > Accept-Language > 默认 ja
· models/i18n.go:Localize* 方法在输出前把 *_ja 覆盖到同名字段,
  前端仍只认 name/title/content 一套字段,页面零改动
· 公开接口 List/GetByID 接入;后台 CRUD 接受并保存 *_ja

前端
· request 拦截器统一带 X-Lang 与 ?lang=,一处生效,不会漏接口
· 后台五个内容表单加「中文(源内容)/ 日本語」两段输入
· 切语言后整页重载(内容是后端按语言给的,不重拉就是旧语言缓存)

数据
· scripts/restore_content_zh.py:中文原文从内容日文化之前的备份读回主列,
  日文搬进 *_ja;已有 *_ja 的行跳过,可重复执行
2026-12-02 00:31:58 +08:00

123 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把内容表的「中文原文」放回原列,把日文搬进 *_ja 列。
分工:
中文列(name/title/content/description/summary/button) = 运营用中文写的源内容
*_ja 列 = 日文版本
公开接口按请求语言挑一列输出,后台两列都能编辑。
中文原文从**内容日文化之前的库备份**里读(默认自动挑最新的 sale.db.bak-contentja-*),
所以不需要手工重录。已有 *_ja 值且非空的行跳过,可重复执行。
用法
python3 restore_content_zh.py --db /mnt/data/sale/data/sale.db --backup /mnt/data/sale/data/sale.db.bak-contentja-xxx --dry-run
python3 restore_content_zh.py --db ... --backup ... --yes
"""
import argparse
import datetime as dt
import glob
import os
import shutil
import sqlite3
import sys
# (表, 中文列, 日文列)
FIELDS = [
("categories", "name", "name_ja"),
("categories", "description", "description_ja"),
("banners", "title", "title_ja"),
("banners", "desc", "desc_ja"),
("banners", "button", "button_ja"),
("announcements", "title", "title_ja"),
("announcements", "content", "content_ja"),
("lotteries", "name", "name_ja"),
("lotteries", "description", "description_ja"),
("lottery_prizes", "name", "name_ja"),
("articles", "title", "title_ja"),
("articles", "summary", "summary_ja"),
("articles", "content", "content_ja"),
]
def pick_backup(db_path):
cands = sorted(glob.glob(db_path + ".bak-contentja-*"))
cands = [c for c in cands if not c.endswith(("-wal", "-shm"))]
return cands[-1] if cands else None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True)
ap.add_argument("--backup", default=None)
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--yes", action="store_true")
args = ap.parse_args()
if not args.dry_run and not args.yes:
sys.exit("写库需要 --yes")
backup_path = args.backup or pick_backup(args.db)
if not backup_path or not os.path.exists(backup_path):
sys.exit("找不到内容日文化之前的备份,请用 --backup 指定")
old = sqlite3.connect(backup_path)
old.execute("PRAGMA busy_timeout = 20000")
new = sqlite3.connect(args.db, isolation_level=None)
new.execute("PRAGMA busy_timeout = 30000")
plan = [] # (表, 列, id, 原中文, 当前值)
for table, zh_col, ja_col in FIELDS:
have = {r[1] for r in new.execute(f'PRAGMA table_info("{table}")')}
if ja_col not in have:
print(f"!! {table}.{ja_col} 不存在 —— 先让应用跑一次 AutoMigrate")
continue
cols = {r[1] for r in old.execute(f'PRAGMA table_info("{table}")')}
if zh_col not in cols:
print(f"!! 备份里没有 {table}.{zh_col}")
continue
origin = dict(old.execute(f'SELECT id, "{zh_col}" FROM "{table}"').fetchall())
for rid, cur_zh, cur_ja in new.execute(
f'SELECT id, "{zh_col}", "{ja_col}" FROM "{table}"'
).fetchall():
if rid not in origin:
continue
zh = origin[rid] or ""
if (cur_ja or "").strip():
continue # 已经有日文,别覆盖
if zh == (cur_zh or ""):
continue # 本来就是中文
plan.append((table, zh_col, ja_col, rid, zh, cur_zh))
print(f"备份:{os.path.basename(backup_path)}")
print(f"需要搬动的字段:{len(plan)} 处")
for table, zh_col, ja_col, rid, zh, cur in plan[:12]:
print(f" {table}#{rid}.{zh_col}: 中文←{str(zh)[:26]!r} 日文→{str(cur)[:26]!r}")
if args.dry_run:
print("\n[dry-run] 未写库")
return
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
for suffix in ("", "-wal", "-shm"):
src = args.db + suffix
if os.path.exists(src):
shutil.copy2(src, f"{args.db}.bak-langcol-{stamp}{suffix}")
print(f"\n已备份:sale.db.bak-langcol-{stamp}")
new.execute("BEGIN IMMEDIATE")
try:
for table, zh_col, ja_col, rid, zh, cur in plan:
new.execute(
f'UPDATE "{table}" SET "{ja_col}" = ?, "{zh_col}" = ? WHERE id = ?',
(cur, zh, rid),
)
new.execute("COMMIT")
except Exception as exc: # noqa: BLE001
new.execute("ROLLBACK")
print("失败已回滚:", exc)
raise
print(f"已搬动 {len(plan)} 处:中文回原列,日文进 *_ja")
if __name__ == "__main__":
main()