66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
|
"""数据库初始化和种子数据脚本"""
|
|
|
|
from app.database import engine, Base, SessionLocal
|
|
from app.models import Joke, JokeType, JokeCrowd, AdminUser
|
|
from passlib.context import CryptContext
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def init_database():
|
|
"""初始化数据库,创建表和种子数据"""
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
if db.query(AdminUser).count() > 0:
|
|
print("Database already initialized, skipping...")
|
|
return
|
|
|
|
admin = AdminUser(username="admin", password_hash=pwd_context.hash("admin123"))
|
|
db.add(admin)
|
|
|
|
types_data = ["冷笑话", "谐音梗", "段子", "图文笑话"]
|
|
type_objects = []
|
|
for name in types_data:
|
|
t = JokeType(name=name)
|
|
db.add(t)
|
|
type_objects.append(t)
|
|
|
|
crowds_data = ["校园", "职场", "家庭", "儿童"]
|
|
crowd_objects = []
|
|
for name in crowds_data:
|
|
c = JokeCrowd(name=name)
|
|
db.add(c)
|
|
crowd_objects.append(c)
|
|
|
|
db.commit()
|
|
|
|
sample_jokes = [
|
|
{"title": "程序员的幽默", "content": "程序员去相亲,女方问:你有什么优点?程序员答:我bug少。女方:...", "type_id": type_objects[1].id, "crowd_id": crowd_objects[1].id},
|
|
{"title": "逻辑笑话", "content": "为什么程序员总是分不清万圣节和圣诞节?因为 Oct 31 = Dec 25", "type_id": type_objects[1].id, "crowd_id": crowd_objects[1].id},
|
|
{"title": "爆笑冷笑话", "content": "有一天小鼠问大鼠:你为什么叫大鼠?因为我是大学生!", "type_id": type_objects[0].id, "crowd_id": crowd_objects[0].id},
|
|
{"title": "职场趣事", "content": "老板问员工:你有什么特长?员工说:我加班不要钱!", "type_id": type_objects[2].id, "crowd_id": crowd_objects[1].id},
|
|
{"title": "儿童趣语", "content": "妈妈问小明:你长大想当什么?小明说:我想当爸爸!", "type_id": type_objects[2].id, "crowd_id": crowd_objects[3].id},
|
|
]
|
|
|
|
for joke_data in sample_jokes:
|
|
joke = Joke(**joke_data, status="approved")
|
|
db.add(joke)
|
|
|
|
db.commit()
|
|
print("Database initialized successfully!")
|
|
print("Admin login: admin / admin123")
|
|
|
|
except Exception as e:
|
|
db.rollback()
|
|
print(f"Error: {e}")
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
init_database()
|