Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
218 lines
11 KiB
Python
218 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
主页内容充实种子脚本:
|
||
1. 给全部用户补 unsplash 人像头像(解决头像全空)
|
||
2. 补热门标签 + article_tags 关联(解决搜索热榜为空)
|
||
3. 新增 5 篇已发布文章(不同作者/分类/话题,发布时间错开,充实主页信息流)
|
||
幂等性:头像按 account 判断;标签按 name 唯一;文章 mask_id 固定为
|
||
art_seedhome + md5(title)[:12],重复执行自动跳过。
|
||
"""
|
||
|
||
import hashlib
|
||
import json
|
||
import subprocess
|
||
import sys
|
||
import uuid
|
||
|
||
PSQL = r"C:\Program Files\PostgreSQL\16\bin\psql.exe"
|
||
DB = ["-h", "127.0.0.1", "-p", "55432", "-U", "postgres", "-d", "article_platform"]
|
||
|
||
|
||
def run_sql(sql):
|
||
full = "SET client_encoding = 'UTF8';\nBEGIN;\n" + sql + "\nCOMMIT;"
|
||
p = subprocess.run([PSQL] + DB + ["-v", "ON_ERROR_STOP=1"],
|
||
input=full.encode("utf-8"), capture_output=True)
|
||
out = p.stdout.decode("utf-8", errors="replace")
|
||
err = p.stderr.decode("utf-8", errors="replace")
|
||
if p.returncode != 0 or "ERROR" in err:
|
||
print("SQL ERROR:\n", err, "\n", out)
|
||
sys.exit(1)
|
||
return out
|
||
|
||
|
||
def query(sql):
|
||
p = subprocess.run([PSQL] + DB + ["-t", "-A", "-c", sql],
|
||
input=sql.encode("utf-8"), capture_output=True)
|
||
return p.stdout.decode("utf-8", errors="replace").strip()
|
||
|
||
|
||
def new_uuid():
|
||
return str(uuid.uuid4())
|
||
|
||
|
||
# ── 1. 用户头像:默认不做照片兜底(字母头像由前端 app-avatar 组件承担),
|
||
# 并清掉历史素材照片,保持全库一致的字母头像风格
|
||
# ── 1. 用户头像
|
||
|
||
# ── 2. 热门标签 ──
|
||
TAGS = ["美食", "旅行", "摄影", "生活记录", "职场", "读书笔记", "运动健身", "数码评测"]
|
||
|
||
# 分类 → 语义标签(用于把现有+新文章挂上标签)
|
||
LINKS = [
|
||
("美食探店", "美食"), ("美食探店", "生活记录"),
|
||
("环球旅行", "旅行"), ("环球旅行", "摄影"),
|
||
("光影摄影", "摄影"), ("光影摄影", "生活记录"),
|
||
("生活美学", "生活记录"), ("生活美学", "读书笔记"),
|
||
("人文阅读", "读书笔记"), ("人文阅读", "职场"),
|
||
("数码科技", "数码评测"),
|
||
]
|
||
|
||
# ── 3. 新文章 ──
|
||
COVERS = [
|
||
"https://images.unsplash.com/photo-1504674900247-0877df9cc836?w=900&q=80",
|
||
"https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=900&q=80",
|
||
"https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=900&q=80",
|
||
"https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=900&q=80",
|
||
"https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=900&q=80",
|
||
]
|
||
|
||
NEW_ARTICLES = [
|
||
{
|
||
"title": "厨房里的节气:立冬那一锅慢慢煨着的萝卜牛腩",
|
||
"abstract": "入冬前的最后一次降温,最适合守着一口砂锅。牛腩焯水去沫,白萝卜滚刀下锅,小火煨足两个钟头,汤色渐渐转浓——做饭这件事,急不得。",
|
||
"cat": "美食探店", "owner": "foodie_cat", "days": 0,
|
||
"views": 1560, "likes": 203, "favs": 87,
|
||
"sections": [
|
||
("text", {"plain_text": "菜市场的萝卜在立冬前后最甜。挑两根沉手的,削皮滚刀切块,和焯过水的牛腩一起下砂锅,只放姜片、一段葱和半勺黄酒。", "text_align": "left"}),
|
||
("text", {"plain_text": "小火煨到第二个钟头,厨房里全是那种让人安心的味道。盛出来撒一把青蒜末,配一碗白米饭,就是冬天的开门仪式。", "text_align": "left"}),
|
||
],
|
||
},
|
||
{
|
||
"title": "通勤路上读完的五本书:把碎片时间还给阅读",
|
||
"abstract": "地铁单程四十分钟,一年下来足够读完二十本书。分享这五本让我在拥挤车厢里忘记刷手机的书,以及一点做读书笔记的笨办法。",
|
||
"cat": "人文阅读", "owner": "design_daily", "days": 1,
|
||
"views": 2310, "likes": 318, "favs": 156,
|
||
"sections": [
|
||
("text", {"plain_text": "读书最难的从来不是读懂,而是开始。我的办法很笨:包里永远放一本纸质书,手机进地铁就收起来。", "text_align": "left"}),
|
||
("text", {"plain_text": "笔记用三段式:一句原文、一句自己的话、一个可以行动的改动。读完就翻,翻完就删,留下的才是自己的。", "text_align": "left"}),
|
||
],
|
||
},
|
||
{
|
||
"title": "把旧笔记本改成家庭影音站的完整记录",
|
||
"abstract": "一块退役的商务本,装上轻量系统接上电视,功耗不到十五瓦却流畅解码 4K。记录整个过程和踩过的坑,附功耗实测。",
|
||
"cat": "数码科技", "owner": "creator_6a906bac", "days": 2,
|
||
"views": 3080, "likes": 442, "favs": 233,
|
||
"sections": [
|
||
("text", {"plain_text": "退役笔记本最大的优势是自带解码性能和静音散热。装好系统后装个播放器,遥控用手机替代,整套成本几乎为零。", "text_align": "left"}),
|
||
("text", {"plain_text": "实测播放 4K 片源 CPU 占用不到四成,整机功耗 12-15W,比电视盒子的体验好出一截。", "text_align": "left"}),
|
||
],
|
||
},
|
||
{
|
||
"title": "清晨六点的城市公园:晨跑一个月拍下的十二个瞬间",
|
||
"abstract": "坚持晨跑一个月,顺手用手机记录下公园里的清晨:打太极的老人、雾里的湖面、第一班公交驶过的声音。运动最好的奖赏,是看见城市醒来。",
|
||
"cat": "生活美学", "owner": "traveler_lin", "days": 3,
|
||
"views": 1870, "likes": 267, "favs": 98,
|
||
"sections": [
|
||
("text", {"plain_text": "六点的公园属于另一种时间:洒水车还没来,湖面浮着薄雾,长椅上有刚铺开太极阵的老人。", "text_align": "left"}),
|
||
("text", {"plain_text": "跑完第十天,不再需要闹钟。身体先醒,然后是天亮,最后才是这座城市。", "text_align": "left"}),
|
||
],
|
||
},
|
||
{
|
||
"title": "周末短途:高铁两小时可达的六座小城清单",
|
||
"abstract": "不用请假、不赶行程,周六早上出发周日傍晚回。这六座高铁两小时圈内的小城,有老街、有湖鲜、有泡了一半就想睡着的温泉。",
|
||
"cat": "环球旅行", "owner": "author_demo", "days": 4,
|
||
"views": 2740, "likes": 389, "favs": 201,
|
||
"sections": [
|
||
("text", {"plain_text": "短途旅行的精髓是降低期待、提高密度:一座老桥、一碗面、一场不赶时间的散步,就值回票价。", "text_align": "left"}),
|
||
("text", {"plain_text": "清单按季节排:春天看油菜花,夏天躲进山里的溪水,秋天吃蟹,冬天泡温泉。", "text_align": "left"}),
|
||
],
|
||
},
|
||
]
|
||
|
||
|
||
def main():
|
||
# 已执行过则跳过(以第一篇的固定 mask 判断)
|
||
probe_mask = "art_seedhome" + hashlib.md5(NEW_ARTICLES[0]["title"].encode()).hexdigest()[:12]
|
||
done = query(f"SELECT count(*) FROM articles WHERE mask_id='{probe_mask}';")
|
||
if int(done) > 0:
|
||
print("SKIP: 种子数据已存在")
|
||
return
|
||
|
||
sql = ""
|
||
|
||
# 头像:清掉素材照片,统一交给前端字母头像兜底
|
||
sql += "UPDATE users SET avatar_url=NULL WHERE avatar_url LIKE 'https://images.unsplash.com%';\n"
|
||
|
||
# 标签
|
||
for name in TAGS:
|
||
heat = 800 + (sum(ord(c) for c in name) * 37) % 4200
|
||
sql += (f"INSERT INTO tags (id, name, article_count, heat_count, status) "
|
||
f"SELECT '{new_uuid()}', '{name}', 0, {heat}, 'active' "
|
||
f"WHERE NOT EXISTS (SELECT 1 FROM tags WHERE name='{name}');\n")
|
||
|
||
# 分类 / 用户映射
|
||
cat_map = {}
|
||
for line in query("SELECT name, id FROM categories ORDER BY sort_order;").split("\n"):
|
||
if "|" in line:
|
||
n, i = line.split("|", 1)
|
||
cat_map[n.strip()] = i.strip()
|
||
user_map = {}
|
||
for line in query("SELECT account, id FROM users WHERE deleted_at IS NULL;").split("\n"):
|
||
if "|" in line:
|
||
a, i = line.split("|", 1)
|
||
user_map[a.strip()] = i.strip()
|
||
topic_ids = [line.split("|", 1)[1].strip()
|
||
for line in query("SELECT name, id FROM topics ORDER BY created_at LIMIT 5;").split("\n")
|
||
if "|" in line]
|
||
admin_id = user_map.get("admin")
|
||
if not admin_id:
|
||
print("FATAL: admin 用户不存在")
|
||
sys.exit(1)
|
||
|
||
# 新文章 + sections
|
||
for idx, art in enumerate(NEW_ARTICLES):
|
||
mask = "art_seedhome" + hashlib.md5(art["title"].encode()).hexdigest()[:12]
|
||
aid = new_uuid()
|
||
cid = cat_map.get(art["cat"]) or next(iter(cat_map.values()))
|
||
owner = user_map.get(art["owner"], admin_id)
|
||
tid = topic_ids[idx % len(topic_ids)] if topic_ids else None
|
||
tid_sql = f"'{tid}'" if tid else "NULL"
|
||
title = art["title"].replace("'", "''")
|
||
abstract = art["abstract"].replace("'", "''")
|
||
sql += f"""
|
||
INSERT INTO articles (
|
||
id, mask_id, title, subtitle, abstract, cover_img_url,
|
||
visual_config, interaction_config, enable_watermark, enable_comment,
|
||
privacy, has_reward, owner_id, category_id, topic_id,
|
||
status, review_status, review_note, reviewed_by, reviewed_at, published_at,
|
||
view_count, like_count, fav_count, comment_count, share_count, schema_version
|
||
) VALUES (
|
||
'{aid}', '{mask}', '{title}', '', '{abstract}', '{COVERS[idx % len(COVERS)]}',
|
||
'{{}}'::jsonb, '{{"enable_comment":true}}'::jsonb, false, true,
|
||
'public', false, '{owner}', '{cid}', {tid_sql},
|
||
'published', 'approved', '优质精选', '{admin_id}', now(), now() - interval '{art['days']} days',
|
||
{art['views']}, {art['likes']}, {art['favs']}, 0, {art['views'] // 20}, 1
|
||
) ON CONFLICT (mask_id) DO NOTHING;
|
||
"""
|
||
for order, (kind, payload) in enumerate(art["sections"]):
|
||
pj = json.dumps(payload, ensure_ascii=False).replace("'", "''")
|
||
sql += (f"INSERT INTO sections (id, article_id, order_index, kind, payload) "
|
||
f"SELECT '{new_uuid()}', id, {order}, '{kind}', '{pj}'::jsonb "
|
||
f"FROM articles WHERE mask_id='{mask}' AND NOT EXISTS "
|
||
f"(SELECT 1 FROM sections s WHERE s.article_id=(SELECT id FROM articles WHERE mask_id='{mask}'));\n")
|
||
|
||
# 标签关联(现有 + 新文章,按分类名映射)
|
||
for cat_name, tag_name in LINKS:
|
||
sql += f"""
|
||
INSERT INTO article_tags (article_id, tag_id)
|
||
SELECT a.id, t.id FROM articles a, tags t
|
||
WHERE a.deleted_at IS NULL AND a.status='published'
|
||
AND a.category_id = (SELECT id FROM categories WHERE name='{cat_name}' LIMIT 1)
|
||
AND t.name='{tag_name}'
|
||
ON CONFLICT DO NOTHING;
|
||
"""
|
||
sql += ("UPDATE tags SET article_count = GREATEST(article_count, "
|
||
"(SELECT count(*) FROM article_tags at WHERE at.tag_id = tags.id));\n")
|
||
|
||
run_sql(sql)
|
||
|
||
print("DONE.",
|
||
query("SELECT 'articles=' || count(*) FROM articles WHERE deleted_at IS NULL AND status='published';"),
|
||
query("SELECT 'tags=' || count(*) FROM tags;"),
|
||
query("SELECT 'avatars=' || count(*) FROM users WHERE avatar_url IS NOT NULL AND avatar_url <> '';"))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|