#!/usr/bin/env python # -*- coding: utf-8 -*- """ FastAPI应用程序入口 为CryptoAI系统提供web API接口层 """ import os import logging import uvicorn from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse import time from typing import Dict, Any from cryptoai.routes.routes import router as api_router # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler("api_server.log"), logging.StreamHandler() ] ) logger = logging.getLogger("fastapi") # 创建FastAPI应用 app = FastAPI( title="CryptoAI API", description="加密货币AI分析系统API接口", version="0.1.0" ) # 添加CORS中间件 app.add_middleware( CORSMiddleware, allow_origins=["*"], # 可以设置为特定域名,如["http://localhost:3000"] allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 添加API路由 app.include_router(api_router) # 请求计时中间件 @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time) return response # 根路由 @app.get("/", tags=["信息"]) async def root() -> Dict[str, Any]: """ API根路径,提供API基本信息 """ return { "name": "CryptoAI API", "version": "0.1.0", "description": "加密货币AI分析系统API接口", "documentation": "/docs", "status": "running" } # 健康检查 @app.get("/health", tags=["信息"]) async def health_check() -> Dict[str, Any]: """ API健康检查接口 """ return { "status": "healthy", "timestamp": time.time() } # 异常处理 @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.error(f"全局异常: {str(exc)}", exc_info=True) return JSONResponse( status_code=500, content={"detail": f"服务器内部错误: {str(exc)}"} ) def start(): """ 启动FastAPI服务器 """ # 获取环境变量或使用默认值 host = os.environ.get("API_HOST", "127.0.0.1") port = int(os.environ.get("API_PORT", 8000)) # 启动服务器 uvicorn.run( "cryptoai.routes.fastapi_app:app", host=host, port=port, reload=False # 生产环境设为False ) if __name__ == "__main__": start()