2.4 KiB
2.4 KiB
请创建以下 3 个文件。backend 目录已存在,但 backend/app/ 需要新建。
文件 1: backend/app/__init__.py
空文件。
文件 2: backend/app/config.py
"""应用配置 — 从环境变量 / .env 读取。"""
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str = "postgresql+asyncpg://hive_admin:changeme@localhost:5432/hive_manage_v3"
jwt_secret: str = "change-me"
jwt_algorithm: str = "HS256"
jwt_expire_minutes: int = 1440
hermes_cli_path: str = "/home/enzo/.local/bin/hermes"
hermes_profiles_root: str = "/home/enzo/.hermes/profiles"
admin_email: str = "admin@zhiwei.local"
admin_password: str = "admin123"
model_config = {"env_file": ".env"}
settings = Settings()
文件 3: backend/app/database.py
"""异步 SQLAlchemy 引擎 + session 工厂。"""
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
engine = create_async_engine(settings.database_url, echo=False)
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncSession:
async with async_session() as session:
yield session
文件 4: backend/app/main.py
"""FastAPI 应用入口。"""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import engine, Base
@asynccontextmanager
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
await engine.dispose()
app = FastAPI(
title="Hive Manage v3",
version="0.1.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/api/v1/health")
async def health_check():
return {"status": "ok"}
创建完成后,执行以下验证:
cat检查每个文件内容cd backend && pip install -e ".[dev]"安装依赖cd backend && python -c "from app.main import app; print('FastAPI app created OK')"验证导入- git add + git commit -m "feat: FastAPI skeleton with config, database, health endpoint"