""" Author: Yutang LI Institution: SIAT-MIC Contact: yt.li2@siat.ac.cn """ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from router.mp_router import router as material_router from router.oqmd_router import router as oqmd_router from router.fairchem_router import router as fairchem_router from error_handlers import ( handle_general_error, handle_http_error, handle_validation_error ) from utils import setup_logging from router.fairchem_router import init_model # 初始化日志配置 setup_logging() # 创建中间件列表 middleware = [ Middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ] app = FastAPI(middleware=middleware) @app.on_event("startup") async def startup_event(): """应用启动时初始化模型""" init_model() # 注册路由 app.include_router(material_router) app.include_router(oqmd_router) app.include_router(fairchem_router) # 添加全局异常处理 @app.exception_handler(Exception) async def global_exception_handler(request, exc): return handle_general_error(exc) @app.exception_handler(ValueError) async def validation_exception_handler(request, exc): return handle_validation_error(exc) @app.exception_handler(ConnectionError) async def http_exception_handler(request, exc): return handle_http_error(exc)