backend_v0.1
This commit is contained in:
50
app/database.py
Normal file
50
app/database.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# database.py
|
||||
import os
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
# 优先从环境变量读取(Docker 部署推荐)
|
||||
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://user:password@db:5432/fastapi_db")
|
||||
|
||||
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, echo=True)
|
||||
AsyncSessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
async def get_db():
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
# 注意:通常不在 get_db 里统一 commit,建议在 endpoint 里手动 commit
|
||||
|
||||
async def init_db():
|
||||
async with engine.begin() as conn:
|
||||
# 导入模型以确保 metadata 注册了表
|
||||
from . import models
|
||||
# 自动创建表
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
# 创建默认管理员用户
|
||||
async with AsyncSessionLocal() as session:
|
||||
from . import auth
|
||||
from sqlalchemy.future import select
|
||||
|
||||
# 检查是否已存在 admin 用户
|
||||
result = await session.execute(
|
||||
select(models.User).where(models.User.username == "admin")
|
||||
)
|
||||
existing_admin = result.scalars().first()
|
||||
|
||||
if not existing_admin:
|
||||
# 创建管理员用户
|
||||
private_key, public_key = auth.generate_key_pair()
|
||||
admin_user = models.User(
|
||||
username="admin",
|
||||
hashed_password=auth.hash_password("admin123"),
|
||||
private_key=private_key,
|
||||
public_key=public_key,
|
||||
is_admin=True,
|
||||
guale=False
|
||||
)
|
||||
session.add(admin_user)
|
||||
await session.commit()
|
||||
print("✅ Default admin user created (username: admin, password: admin123)")
|
||||
Reference in New Issue
Block a user