abab985769
- 后端新增中间件限制请求体最大为8MB,超出返回413错误 - nginx配置添加client_max_body_size为8m以支持8MB最大上传 - 更新favicon.svg图标样式 - 模型列表页默认分页大小由10改为50,提高一次加载条目数
99 lines
2.6 KiB
Python
99 lines
2.6 KiB
Python
from fastapi import FastAPI, Depends, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
import os
|
|
import logging
|
|
from dotenv import load_dotenv
|
|
|
|
from database import engine, Base
|
|
from routes import brands_router, models_router, ota_router
|
|
from routes.auth import router as auth_router
|
|
from security import get_current_user
|
|
|
|
# Load environment variables
|
|
load_dotenv(override=True)
|
|
|
|
# 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__)
|
|
|
|
# Create database tables (only if tables don't exist)
|
|
try:
|
|
logger.info("Creating database tables...")
|
|
Base.metadata.create_all(bind=engine)
|
|
logger.info("Database tables created successfully")
|
|
except Exception as e:
|
|
logger.error(f"Warning: Could not create tables: {e}")
|
|
logger.error("Continuing without table creation...")
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title=os.getenv("APP_NAME", "Audio Dashboard API"),
|
|
description="耳机品牌与型号管理平台后端 API",
|
|
version="1.0.0"
|
|
)
|
|
|
|
# 限制请求体最大 8MB
|
|
MAX_BODY_SIZE = 8 * 1024 * 1024 # 8MB
|
|
|
|
|
|
@app.middleware("http")
|
|
async def limit_body_size(request: Request, call_next):
|
|
content_length = request.headers.get("content-length")
|
|
if content_length and int(content_length) > MAX_BODY_SIZE:
|
|
return JSONResponse(
|
|
status_code=413,
|
|
content={"detail": "上传文件大小超过 8MB 限制"},
|
|
)
|
|
response = await call_next(request)
|
|
return response
|
|
|
|
|
|
# Configure CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"], # 生产环境应该限制具体域名
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# Include routers(业务接口需登录;登录接口除外)
|
|
app.include_router(auth_router)
|
|
app.include_router(brands_router, dependencies=[Depends(get_current_user)])
|
|
app.include_router(models_router, dependencies=[Depends(get_current_user)])
|
|
app.include_router(ota_router, dependencies=[Depends(get_current_user)])
|
|
|
|
|
|
@app.get("/")
|
|
def root():
|
|
"""根路径"""
|
|
return {
|
|
"message": "欢迎使用 Audio Dashboard API",
|
|
"docs": "/docs",
|
|
"redoc": "/redoc"
|
|
}
|
|
|
|
|
|
@app.get("/health")
|
|
def health_check():
|
|
"""健康检查1"""
|
|
return {"status": "healthy"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(
|
|
"main:app",
|
|
host="0.0.0.0",
|
|
port=8083,
|
|
reload=False
|
|
)
|