2c9e0f0015
- bgm_seed_data.json: 129 首 BGM 元数据(含七牛云 URL) - seed_bgm.py: 部署环境初始化脚本,容器内直接运行
72 lines
2.0 KiB
Python
72 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
BGM 种子数据导入脚本
|
||
==================
|
||
|
||
用于部署环境初始化 BGM 数据。读取同目录下的 bgm_seed_data.json,
|
||
将 129 首系统背景音乐的元数据(含七牛云 URL)写入数据库。
|
||
|
||
执行方式(在 API 容器内):
|
||
python scripts/seed_bgm.py
|
||
|
||
环境变量依赖:
|
||
DATABASE_URL — 同应用配置,容器启动时已注入
|
||
"""
|
||
|
||
import asyncio
|
||
import json
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
project_root = Path(__file__).parent.parent
|
||
sys.path.insert(0, str(project_root))
|
||
|
||
from dotenv import load_dotenv
|
||
|
||
load_dotenv()
|
||
|
||
from sqlalchemy import select, func
|
||
from app.db.session import AsyncSessionLocal
|
||
from app.models.bgm_music import BgmMusic
|
||
|
||
|
||
SEED_FILE = Path(__file__).parent / "bgm_seed_data.json"
|
||
|
||
|
||
async def seed_bgm():
|
||
if not SEED_FILE.exists():
|
||
print(f"错误: 种子数据文件不存在: {SEED_FILE}")
|
||
return
|
||
|
||
with open(SEED_FILE, "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
|
||
async with AsyncSessionLocal() as session:
|
||
# 检查是否已有数据
|
||
count = await session.scalar(select(func.count(BgmMusic.id)))
|
||
if count and count > 0:
|
||
print(f"数据库中已有 {count} 条 BGM 记录,跳过导入")
|
||
print("如需强制重新导入,请先清空 mjk_bgm_musics 表")
|
||
return
|
||
|
||
for idx, item in enumerate(data):
|
||
bgm = BgmMusic(
|
||
title=item["title"],
|
||
artist=item.get("artist"),
|
||
category=item["category"],
|
||
file_path=item["file_path"],
|
||
url=item.get("url"),
|
||
duration=item.get("duration"),
|
||
status=item.get("status", "active"),
|
||
sort_order=item.get("sort_order", idx),
|
||
)
|
||
session.add(bgm)
|
||
|
||
await session.commit()
|
||
print(f"种子数据导入完成,共 {len(data)} 首")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
asyncio.run(seed_bgm())
|