crypto.ai/cryptoai/routes/fastapi_app.py
2025-06-11 19:45:53 +08:00

122 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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.utils.db_manager import init_db
from cryptoai.routes.user import router as user_router
from cryptoai.routes.adata import router as adata_router
from cryptoai.routes.crypto import router as crypto_router
from cryptoai.routes.platform import router as platform_router
from cryptoai.routes.analysis import router as analysis_router
from cryptoai.routes.alltick import router as alltick_router
from cryptoai.routes.payment import router as payment_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(platform_router, prefix="/platform", tags=["平台信息"])
app.include_router(user_router, prefix="/user", tags=["用户管理"])
app.include_router(adata_router, prefix="/adata", tags=["A股数据"])
app.include_router(crypto_router, prefix="/crypto", tags=["加密货币数据"])
app.include_router(analysis_router, prefix="/analysis", tags=["分析历史"])
app.include_router(alltick_router, prefix="/alltick", tags=["AllTick数据"])
app.include_router(payment_router, prefix="/payment", tags=["支付"])
# 请求计时中间件
@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=True # 生产环境设为False
)
if __name__ == "__main__":
init_db()
start()