新增nacos 配置 测试
All checks were successful
git commit AiDA python develop 分支构建部署 / scheduled_deploy (push) Has been skipped
All checks were successful
git commit AiDA python develop 分支构建部署 / scheduled_deploy (push) Has been skipped
This commit is contained in:
64
app/main.py
64
app/main.py
@@ -1,5 +1,5 @@
|
||||
# 1. 这里的顺序至关重要!必须在最顶端
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
try:
|
||||
import asyncore
|
||||
@@ -10,16 +10,14 @@ except ImportError:
|
||||
import logging.config
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
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
|
||||
# from app.core.record_api_count import count_api_calls
|
||||
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 dotenv import load_dotenv
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
logging.config.dictConfig(LOGGER_CONFIG_DICT)
|
||||
@@ -27,33 +25,28 @@ logging.getLogger("pika").setLevel(logging.WARNING)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
@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("✅ 服务已优雅关闭")
|
||||
|
||||
|
||||
def get_application() -> FastAPI:
|
||||
application = FastAPI(
|
||||
docs_url="/docs",
|
||||
redoc_url='/re-docs',
|
||||
openapi_url=f"/openapi.json",
|
||||
description='''
|
||||
Base frame with FastAPI
|
||||
- Super Resolution API
|
||||
|
||||
'''
|
||||
)
|
||||
application.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
# application.middleware("http")(count_api_calls)
|
||||
application.include_router(router=router)
|
||||
return application
|
||||
|
||||
|
||||
app = get_application()
|
||||
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)
|
||||
@@ -64,5 +57,16 @@ async def http_exception_handler(exc: HTTPException):
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
Reference in New Issue
Block a user