2026-03-04 18:17:34 +08:00
|
|
|
from fastapi import FastAPI
|
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
import os
|
2026-03-17 14:20:08 +08:00
|
|
|
import logging
|
2026-03-04 18:17:34 +08:00
|
|
|
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
from database import engine, Base
|
|
|
|
|
from routes import brands_router, models_router
|
|
|
|
|
|
|
|
|
|
# Load environment variables
|
|
|
|
|
load_dotenv()
|
|
|
|
|
|
2026-03-17 14:20:08 +08:00
|
|
|
# Configure logging
|
|
|
|
|
logging.basicConfig(
|
|
|
|
|
level=logging.INFO,
|
|
|
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
|
|
|
handlers=[
|
|
|
|
|
logging.StreamHandler(), # 输出到控制台
|
|
|
|
|
logging.FileHandler('logs/app.log', encoding='utf-8') # 输出到文件
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-03-04 18:17:34 +08:00
|
|
|
# Create database tables (only if tables don't exist)
|
|
|
|
|
try:
|
2026-03-17 14:20:08 +08:00
|
|
|
logger.info("Creating database tables...")
|
2026-03-04 18:17:34 +08:00
|
|
|
Base.metadata.create_all(bind=engine)
|
2026-03-17 14:20:08 +08:00
|
|
|
logger.info("Database tables created successfully")
|
2026-03-04 18:17:34 +08:00
|
|
|
except Exception as e:
|
2026-03-17 14:20:08 +08:00
|
|
|
logger.error(f"Warning: Could not create tables: {e}")
|
|
|
|
|
logger.error("Continuing without table creation...")
|
2026-03-04 18:17:34 +08:00
|
|
|
|
|
|
|
|
# Create FastAPI app
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
title=os.getenv("APP_NAME", "Audio Dashboard API"),
|
|
|
|
|
description="耳机品牌与型号管理平台后端 API",
|
|
|
|
|
version="1.0.0"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Configure CORS
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=["*"], # 生产环境应该限制具体域名
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Include routers
|
|
|
|
|
app.include_router(brands_router)
|
|
|
|
|
app.include_router(models_router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/")
|
|
|
|
|
def root():
|
|
|
|
|
"""根路径"""
|
|
|
|
|
return {
|
|
|
|
|
"message": "欢迎使用 Audio Dashboard API",
|
|
|
|
|
"docs": "/docs",
|
|
|
|
|
"redoc": "/redoc"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/health")
|
|
|
|
|
def health_check():
|
|
|
|
|
"""健康检查"""
|
|
|
|
|
return {"status": "healthy"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
import uvicorn
|
|
|
|
|
uvicorn.run(
|
|
|
|
|
"main:app",
|
|
|
|
|
host="0.0.0.0",
|
|
|
|
|
port=8002,
|
|
|
|
|
reload=False
|
|
|
|
|
)
|