Files
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

79 lines
2.6 KiB
Python

"""
一次性修复三个产品页的图片:
1. 从 website-old 拷贝图片到 202605 目录(加前缀避免重名)
2. 更新数据库内容中的图片路径
"""
import sqlite3
import shutil
import os
import re
BASE = "/var/www/new-media-platform/website-new/storage/admin/images"
DEST = f"{BASE}/202605"
os.makedirs(DEST, exist_ok=True)
DB = "/var/www/new-media-platform/website-new/backend/cms.db"
# 三个产品:数据库ID, 旧路径前缀, 源图片目录, 新文件名前缀
PRODUCTS = [
(345, "products/niaojianyun", "/home/ubuntu/website-old/src/assets/img/product-niaojianyun", "njjy"),
(346, "products/wudaifu", "/home/ubuntu/website-old/src/assets/img/product-wudaifu", "wdf"),
(347, "products/wushizhi", "/home/ubuntu/website-old/src/assets/img/product-wushizhi", "wsz"),
]
conn = sqlite3.connect(DB)
cur = conn.cursor()
for aid, old_prefix, src_dir, prefix in PRODUCTS:
print(f"\n=== 处理 ID={aid}, 前缀={prefix} ===")
# 获取文章内容
cur.execute("SELECT content FROM articles WHERE id=?", (aid,))
row = cur.fetchone()
if not row or not row[0]:
print(f" ✗ 文章 {aid} 无内容")
continue
content = row[0]
# 找出所有需要迁移的图片
old_pattern = rf'/storage/admin/images/{old_prefix}/([^"\']+)'
matches = list(re.finditer(old_pattern, content))
print(f" 找到 {len(matches)} 个图片引用")
new_content = content
for m in matches:
old_filename = m.group(1)
new_filename = f"{prefix}-{old_filename}"
src_path = os.path.join(src_dir, old_filename)
dst_path = os.path.join(DEST, new_filename)
old_full = m.group(0)
new_full = f"/storage/admin/images/202605/{new_filename}"
# 拷贝文件
if os.path.exists(src_path):
shutil.copy2(src_path, dst_path)
print(f" ✓ {old_filename} → {new_filename}")
else:
# 也许已经在 products/ 目录下
alt_src = os.path.join(BASE, old_prefix, old_filename)
if os.path.exists(alt_src):
shutil.copy2(alt_src, dst_path)
print(f" ✓ {old_filename} → {new_filename} (from products/)")
else:
print(f" ✗ 源文件不存在: {old_filename}")
continue
# 替换路径
new_content = new_content.replace(old_full, new_full)
# 更新数据库
cur.execute("UPDATE articles SET content=? WHERE id=?", (new_content, aid))
print(f" 数据库已更新 (ID={aid})")
conn.commit()
conn.close()
print("\n=== 完成 ===")
print(f"所有图片已拷贝到: {DEST}/")