Files
AiDA_Python/app/main.py

91 lines
2.2 KiB
Python
Raw Normal View History

2026-04-28 17:17:29 +08:00
# 1. 这里的顺序至关重要!必须在最顶端
import sys
2026-04-23 17:10:22 +08:00
from contextlib import asynccontextmanager
2026-04-24 10:17:42 +08:00
2026-04-28 17:17:29 +08:00
# from app.core.nacos_config import load_nacos_config, register_server, deregister_server
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-28 17:17:29 +08:00
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi.responses import JSONResponse
2024-03-20 11:44:15 +08:00
from app.api.api_route import router
2026-04-28 17:17:29 +08:00
from app.core.config import settings
# from app.core.record_api_count import count_api_calls
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
2026-04-28 17:17:29 +08:00
from dotenv import load_dotenv
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
logger = logging.getLogger(__name__)
2026-04-28 17:17:29 +08:00
load_dotenv()
# @asynccontextmanager
# async def lifespan(app: FastAPI):
# try:
# load_nacos_config()
# register_server()
#
# yield
# finally:
# deregister_server()
# logger.info("lifespan down")
def get_application() -> FastAPI:
application = FastAPI(
# lifespan=lifespan,
docs_url="/docs",
redoc_url='/re-docs',
openapi_url=f"/openapi.json",
description='''
Base frame with FastAPI
- Super Resolution API
'''
2026-04-24 10:17:42 +08:00
)
2026-04-28 17:17:29 +08:00
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()
2024-06-13 14:31:14 +08:00
@app.exception_handler(HTTPException)
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-28 17:17:29 +08:00
@app.get("/health", operation_id="health")
2026-04-23 17:10:22 +08:00
async def health():
2026-04-28 17:17:29 +08:00
logger.info("health check")
return {"ok": True, "env": settings.APP_ENV}
2026-04-23 17:10:22 +08:00
2024-03-20 11:44:15 +08:00
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=settings.PORT)