You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
from config import settings
from utils import setup_logging
from routers import (
market_router,
sentiment_router,
momentum_router,
highlow_router,
stock_router,
news_router,
)
from websocket import websocket_handler, manager
from adapters import DataAdapterFactory
from models import ApiResponse
setup_logging()
@asynccontextmanager
async def lifespan(app: FastAPI):
await manager.start_broadcast_loop()
yield
await manager.stop_broadcast_loop()
await DataAdapterFactory.close_all()
app = FastAPI(
title=settings.APP_NAME,
description="A股智投后端API服务提供市场数据、情绪指标、版块动量、AI分析等功能",
version="1.0.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins_list,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(market_router)
app.include_router(sentiment_router)
app.include_router(momentum_router)
app.include_router(highlow_router)
app.include_router(stock_router)
app.include_router(news_router)
@app.get("/", response_model=ApiResponse, tags=["系统"])
async def root():
return ApiResponse(
success=True,
data={
"name": settings.APP_NAME,
"version": "1.0.0",
"status": "running",
},
message="欢迎使用A股智投API服务",
)
@app.get("/health", response_model=ApiResponse, tags=["系统"])
async def health_check():
return ApiResponse(
success=True,
data={"status": "healthy"},
)
@app.websocket("/ws/realtime")
async def websocket_endpoint(websocket: WebSocket):
await websocket_handler(websocket)
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500,
content={
"success": False,
"error": str(exc),
"message": "服务器内部错误",
},
)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host=settings.APP_HOST,
port=settings.APP_PORT,
reload=settings.APP_DEBUG,
log_level=settings.LOG_LEVEL.lower(),
)