Files
AiDA_Python/app/main.py
zcr cfbd9e47ac
All checks were successful
git commit AiDA python develop 分支构建部署 / scheduled_deploy (push) Has been skipped
新增nacos 配置 测试
2026-04-23 17:10:22 +08:00

73 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sys
from contextlib import asynccontextmanager
try:
import asyncore
except ImportError:
import pyasyncore
sys.modules['asyncore'] = pyasyncore
import logging.config
import uvicorn
from fastapi import FastAPI, Depends
from fastapi import HTTPException
from fastapi.responses import JSONResponse
from app.api.api_route import router
from app.core.config import settings, load_nacos_config, get_settings, Settings, register_service_to_nacos, deregister_service_from_nacos, nacos_initialized_successfully
from app.schemas.response_template import ResponseModel
from logging_env import LOGGER_CONFIG_DICT
from starlette.middleware.cors import CORSMiddleware
logging.config.dictConfig(LOGGER_CONFIG_DICT)
logging.getLogger("pika").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动阶段
try:
await load_nacos_config() # 里面已包含配置加载 + 服务注册
logger.info(f"🚀 服务启动完成 | SERVE_ENV={settings.SERVE_ENV} | PORT={settings.PORT} | Nacos={'已连接' if nacos_initialized_successfully else '未连接(使用.env'}")
except Exception as e:
logger.error(f"启动时发生严重错误: {e}")
raise
yield
# 关闭阶段(优雅下线)
await deregister_service_from_nacos()
# 如果有 nacos client可以在这里 shutdown
logger.info("✅ 服务已优雅关闭")
app = FastAPI(lifespan=lifespan, docs_url="/docs", redoc_url='/re-docs', openapi_url=f"/openapi.json", description=''' Base frame with FastAPI - Super Resolution API ''')
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
app.include_router(router=router)
@app.exception_handler(HTTPException)
async def http_exception_handler(exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content=ResponseModel(code=exc.status_code, msg=exc.detail, data=exc.detail).dict()
)
@app.get("/health")
async def health():
return {"status": "ok", "env": settings.SERVE_ENV}
@app.get("/config")
async def show_config(s: Settings = Depends(get_settings)):
"""查看当前完整配置(生产环境建议加权限)"""
return s.model_dump()
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=settings.PORT)