本次提交内容包括: 1. 替换13个二级分类为真实商业实拍图,同步更新本地与线上数据库 2. 新增会员拨打额度耗尽引导开通会员功能 3. 优化发布页分类选择逻辑,增加会员权益展示 4. 修复分类名称显示问题,完善相关交互逻辑 5. 新增图片同步工具脚本,确保线上线下数据一致性
179 行
6.6 KiB
Python
179 行
6.6 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
将 13 张真实商业摄影实拍图更新至本地与线上数据库,并 SFTP 上传至线上服务器
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
import io
|
||
import json
|
||
import time
|
||
import paramiko
|
||
import pymysql
|
||
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||
|
||
LOCAL_ROOT = r"D:\Softwares\phpstudy_pro\WWW\fenleixinxi"
|
||
JSON_FILE = os.path.join(LOCAL_ROOT, "tools", "real_photos_result.json")
|
||
|
||
REMOTE_HOST = "8.137.181.63"
|
||
REMOTE_PORT = 22
|
||
REMOTE_USER = "root"
|
||
REMOTE_PASS = "liyanxia@6688"
|
||
REMOTE_ROOT = "/www/wwwroot/fenleixinxi.gzyakj.com.cn"
|
||
DB_USER = "fenleixinxi"
|
||
DB_PASS = "fenleixinxi"
|
||
DB_NAME = "fenleixinxi"
|
||
|
||
LOCAL_DB_HOST = "127.0.0.1"
|
||
LOCAL_DB_PORT = 3307
|
||
|
||
def ssh_exec(client, cmd):
|
||
stdin, stdout, stderr = client.exec_command(cmd)
|
||
out = stdout.read().decode("utf-8", errors="replace").strip()
|
||
err = stderr.read().decode("utf-8", errors="replace").strip()
|
||
return out, err
|
||
|
||
def main():
|
||
with open(JSON_FILE, "r", encoding="utf-8") as f:
|
||
photo_list = json.load(f)
|
||
|
||
print(f"=== [1/4] 更新本地数据库 fa_fc_category 与 fa_attachment ({len(photo_list)} 项) ===")
|
||
conn = pymysql.connect(
|
||
host=LOCAL_DB_HOST,
|
||
port=LOCAL_DB_PORT,
|
||
user=DB_USER,
|
||
password=DB_PASS,
|
||
database=DB_NAME,
|
||
charset="utf8mb4",
|
||
autocommit=True
|
||
)
|
||
|
||
with conn.cursor() as cur:
|
||
now_ts = int(time.time())
|
||
for item in photo_list:
|
||
cat_id = item['id']
|
||
url = item['rel_url']
|
||
size = item['size']
|
||
sha1 = item['sha1']
|
||
filename = item['filename']
|
||
|
||
# 更新分类表
|
||
cur.execute("UPDATE fa_fc_category SET image = %s, updatetime = %s WHERE id = %s", (url, now_ts, cat_id))
|
||
|
||
# 插入/更新 attachment 表
|
||
cur.execute("SELECT id FROM fa_attachment WHERE url = %s LIMIT 1", (url,))
|
||
att = cur.fetchone()
|
||
if not att:
|
||
cur.execute("""
|
||
INSERT INTO fa_attachment
|
||
(category, admin_id, user_id, url, imagewidth, imageheight, imagetype, imageframes, filename, filesize, mimetype, createtime, updatetime, uploadtime, storage, sha1)
|
||
VALUES
|
||
('category', 1, 0, %s, 240, 240, 'jpg', 0, %s, %s, 'image/jpeg', %s, %s, %s, 'local', %s)
|
||
""", (url, filename, size, now_ts, now_ts, now_ts, sha1))
|
||
|
||
print(f" ✓ 本地更新: [{item['name']}] (ID:{cat_id}) -> {url}")
|
||
|
||
# 读取本地最新 category 和 attachment
|
||
with conn.cursor() as cur:
|
||
cur.execute("SELECT * FROM fa_fc_category;")
|
||
cat_rows = cur.fetchall()
|
||
cur.execute("DESCRIBE fa_fc_category;")
|
||
cat_cols = [f[0] for f in cur.fetchall()]
|
||
|
||
cur.execute("SELECT * FROM fa_attachment WHERE url LIKE '/uploads/20261028/%.jpg';")
|
||
att_rows = cur.fetchall()
|
||
cur.execute("DESCRIBE fa_attachment;")
|
||
att_cols = [f[0] for f in cur.fetchall()]
|
||
|
||
conn.close()
|
||
|
||
print("\n=== [2/4] 连接线上服务器并通过 SFTP 上传真实照片文件 ===")
|
||
ssh = paramiko.SSHClient()
|
||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||
ssh.connect(REMOTE_HOST, port=REMOTE_PORT, username=REMOTE_USER, password=REMOTE_PASS, timeout=30)
|
||
print("✓ 远程 SSH 连接成功")
|
||
|
||
sftp = ssh.open_sftp()
|
||
remote_upload_dir = f"{REMOTE_ROOT}/public/uploads/20261028"
|
||
ssh_exec(ssh, f"mkdir -p {remote_upload_dir}")
|
||
|
||
for item in photo_list:
|
||
local_path = item['local']
|
||
rel_url = item['rel_url'].lstrip('/')
|
||
remote_path = f"{REMOTE_ROOT}/public/{rel_url}"
|
||
|
||
sftp.put(local_path, remote_path)
|
||
ssh_exec(ssh, f"chown www:www {remote_path}")
|
||
print(f" ✓ SFTP 已上传: {remote_path} ({os.path.basename(local_path)})")
|
||
|
||
sftp.close()
|
||
|
||
print("\n=== [3/4] 同步更新线上数据库 fa_fc_category 与 fa_attachment ===")
|
||
sync_sqls = ["SET FOREIGN_KEY_CHECKS = 0;"]
|
||
|
||
# 全量同步分类
|
||
sync_sqls.append("TRUNCATE TABLE fa_fc_category;")
|
||
col_str = ", ".join([f"`{c}`" for c in cat_cols])
|
||
for row in cat_rows:
|
||
val_list = []
|
||
for v in row:
|
||
if v is None:
|
||
val_list.append("NULL")
|
||
elif isinstance(v, (int, float)):
|
||
val_list.append(str(v))
|
||
else:
|
||
esc = str(v).replace("\\", "\\\\").replace("'", "\\'")
|
||
val_list.append(f"'{esc}'")
|
||
sync_sqls.append(f"INSERT INTO fa_fc_category ({col_str}) VALUES ({', '.join(val_list)});")
|
||
|
||
# 插入 attachment
|
||
if att_rows:
|
||
att_col_str = ", ".join([f"`{c}`" for c in att_cols])
|
||
for row in att_rows:
|
||
val_list = []
|
||
for v in row:
|
||
if v is None:
|
||
val_list.append("NULL")
|
||
elif isinstance(v, (int, float)):
|
||
val_list.append(str(v))
|
||
else:
|
||
esc = str(v).replace("\\", "\\\\").replace("'", "\\'")
|
||
val_list.append(f"'{esc}'")
|
||
sync_sqls.append(f"INSERT IGNORE INTO fa_attachment ({att_col_str}) VALUES ({', '.join(val_list)});")
|
||
|
||
sync_sqls.append("SET FOREIGN_KEY_CHECKS = 1;")
|
||
full_sql = "\n".join(sync_sqls)
|
||
|
||
mysql_cmd = f'mysql -u{DB_USER} -p{DB_PASS} --default-character-set=utf8mb4 {DB_NAME} 2>/dev/null <<\'SQLEOF\'\n{full_sql}\nSQLEOF'
|
||
out, err = ssh_exec(ssh, mysql_cmd)
|
||
if err and "error" in err.lower():
|
||
print(f"✗ 线上数据库更新失败: {err}")
|
||
else:
|
||
print("✓ 线上数据库已更新全部真实实拍照路径与附件数据!")
|
||
|
||
print("\n=== [4/4] 清理缓存并校验真实实拍照访问 ===")
|
||
ssh_exec(ssh, f"rm -rf {REMOTE_ROOT}/runtime/temp/* {REMOTE_ROOT}/runtime/cache/*")
|
||
|
||
# 抽样验证 2 张真实照片的 HTTP 返回码
|
||
for sample in photo_list[:2]:
|
||
test_url = f"https://fenleixinxi.gzyakj.com.cn{sample['rel_url']}"
|
||
cmd_curl = f"curl -s -o /dev/null -w '%{{http_code}}' -k '{test_url}'"
|
||
code, _ = ssh_exec(ssh, cmd_curl)
|
||
print(f" 真实照片 [{sample['name']}] HTTP 校验 ({test_url}): HTTP {code}")
|
||
|
||
# 线上分类接口校验
|
||
cmd_api = "curl -s -k 'https://fenleixinxi.gzyakj.com.cn/api/v1/home/categories'"
|
||
api_res, _ = ssh_exec(ssh, cmd_api)
|
||
if photo_list[0]['rel_url'] in api_res:
|
||
print(" ✓ 线上分类接口已成功返回最新真实实拍照 URL!")
|
||
else:
|
||
print(f" 接口返回采样: {api_res[:200]}")
|
||
|
||
ssh.close()
|
||
print("\n✓ 真实照片更新与线上同步圆满完成!")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|