增加接口文档禁用

This commit is contained in:
liangtianyu
2025-12-03 10:24:55 +08:00
parent 099f7f44a2
commit f4b40e7ff3
2 changed files with 32 additions and 21 deletions

View File

@@ -29,6 +29,7 @@ class Settings(BaseSettings):
app_name: str = "AI Talk Callback API"
environment: str = "production" # 环境: production, test, development
debug: bool = False
disable_docs: bool = False
class Config:
env_file = ".env"

24
main.py
View File

@@ -13,6 +13,7 @@ from app.logger import get_logger, LoggerManager
LoggerManager.setup_logging()
logger = get_logger("main")
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时初始化
@@ -51,7 +52,18 @@ async def lifespan(app: FastAPI):
app = FastAPI(
title=settings.app_name,
version="1.0.0",
lifespan=lifespan
lifespan=lifespan,
docs_url=(
"/docs"
if not settings.disable_docs and settings.environment != "production"
else None
),
redoc_url=(
"/redoc"
if not settings.disable_docs and settings.environment != "production"
else None
),
openapi_url="/openapi.json" if not settings.disable_docs else None,
)
# 添加CORS中间件
@@ -73,6 +85,7 @@ async def root():
if settings.environment == "production":
logger.warning("🚫 生产环境下禁止访问根接口")
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Not Found")
logger.info("📝 根接口被访问")
@@ -85,6 +98,7 @@ async def health_check():
if settings.environment == "production":
logger.warning("🚫 生产环境下禁止访问健康检查接口")
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Not Found")
logger.debug("💓 健康检查接口被访问")
@@ -93,9 +107,5 @@ async def health_check():
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=settings.debug
)
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=settings.debug)