Files

50 lines
1.5 KiB
Python
Raw Permalink Normal View History

2026-08-22 22:28:41 +08:00
"""
博主账号初始化脚本。
用法:
1. 在 .env 中配置 BLOGGER_USERNAME / BLOGGER_EMAIL / BLOGGER_PASSWORD
2. 运行:python -m backend.seed
脚本会创建全局唯一博主账号(bcrypt 哈希存储密码);已存在则跳过。
"""
import os
from .auth import hash_password
from .database import PROJECT_ROOT, SessionLocal, init_db
from .models import ROLE_BLOGGER, User
def seed_blogger() -> None:
"""创建唯一博主账号(已存在则跳过)。"""
username = os.getenv("BLOGGER_USERNAME", "").strip()
email = os.getenv("BLOGGER_EMAIL", "").strip()
password = os.getenv("BLOGGER_PASSWORD", "")
if not (username and email and password):
raise SystemExit("请在 .env 中配置 BLOGGER_USERNAME / BLOGGER_EMAIL / BLOGGER_PASSWORD")
if "@" not in email:
raise SystemExit("BLOGGER_EMAIL 格式不正确")
init_db()
db = SessionLocal()
try:
exists = db.query(User).filter((User.email == email) | (User.username == username)).first()
if exists is not None:
print(f"博主账号已存在(id={exists.id}, username={exists.username}),跳过创建")
return
blogger = User(
email=email,
username=username,
password_hash=hash_password(password),
role=ROLE_BLOGGER,
)
db.add(blogger)
db.commit()
print(f"博主账号创建成功(id={blogger.id}, username={blogger.username}")
finally:
db.close()
if __name__ == "__main__":
seed_blogger()