2025-12-30 16:49:08 +08:00
import sys
2026-04-23 17:10:22 +08:00
from contextlib import asynccontextmanager
2025-12-30 16:49:08 +08:00
try :
import asyncore
except ImportError :
import pyasyncore
sys . modules [ ' asyncore ' ] = pyasyncore
2024-03-20 11:44:15 +08:00
import logging . config
import uvicorn
2026-04-23 17:10:22 +08:00
from fastapi import FastAPI , Depends
2025-12-30 16:49:08 +08:00
from fastapi import HTTPException
2025-02-28 16:26:44 +08:00
from fastapi . responses import JSONResponse
2024-03-20 11:44:15 +08:00
from app . api . api_route import router
2026-04-23 17:10:22 +08:00
from app . core . config import settings , load_nacos_config , get_settings , Settings , register_service_to_nacos , deregister_service_from_nacos , nacos_initialized_successfully
2024-06-13 14:31:14 +08:00
from app . schemas . response_template import ResponseModel
2024-03-20 11:44:15 +08:00
from logging_env import LOGGER_CONFIG_DICT
2025-12-30 16:49:08 +08:00
from starlette . middleware . cors import CORSMiddleware
2024-03-20 11:44:15 +08:00
logging . config . dictConfig ( LOGGER_CONFIG_DICT )
2024-06-03 11:57:13 +08:00
logging . getLogger ( " pika " ) . setLevel ( logging . WARNING )
2024-03-20 11:44:15 +08:00
2025-02-28 16:26:44 +08:00
logger = logging . getLogger ( __name__ )
2025-12-30 16:49:08 +08:00
2026-04-23 17:10:22 +08:00
@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
2024-03-20 11:44:15 +08:00
2026-04-23 17:10:22 +08:00
yield
2024-03-20 11:44:15 +08:00
2026-04-23 17:10:22 +08:00
# 关闭阶段(优雅下线)
await deregister_service_from_nacos ( )
# 如果有 nacos client, 可以在这里 shutdown
logger . info ( " ✅ 服务已优雅关闭 " )
2024-03-20 11:44:15 +08:00
2026-04-23 17:10:22 +08:00
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 )
2024-06-13 14:31:14 +08:00
@app.exception_handler ( HTTPException )
2025-12-30 16:49:08 +08:00
async def http_exception_handler ( exc : HTTPException ) :
2024-06-13 14:31:14 +08:00
return JSONResponse (
status_code = exc . status_code ,
content = ResponseModel ( code = exc . status_code , msg = exc . detail , data = exc . detail ) . dict ( )
)
2026-04-23 17:10:22 +08:00
@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 ( )
2024-03-20 11:44:15 +08:00
if __name__ == ' __main__ ' :
2025-12-30 16:49:08 +08:00
uvicorn . run ( app , host = " 0.0.0.0 " , port = settings . PORT )