- charts.py: serve OHLCV bars & trades from Postgres (klines/trades tables written by indexer), no synthetic data - entities.py: add TradeModel/KlineModel matching indexer schema - main.py: idempotent create_all on startup - config.py: unify default DATABASE_URL with docker-compose/indexer
66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from app.config import settings
|
|
from app.api.routes.api import api_router
|
|
from app.api.routes.charts import kline_router
|
|
from app.api.dependencies import engine
|
|
from app.models.entities import Base
|
|
from app.ws.manager import ws_manager
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
|
logger = logging.getLogger("WTFX-Backend")
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
logger.info(f"Starting {settings.PROJECT_NAME} v{settings.VERSION} [{settings.ENVIRONMENT}]")
|
|
# 幂等建表(含 Indexer 写入的 klines/trades),避免依赖外部建表步骤
|
|
try:
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
logger.info("Database tables ensured.")
|
|
except Exception as e:
|
|
logger.error(f"Failed to ensure database tables: {e}")
|
|
yield
|
|
logger.info("Shutting down WTFX Backend service...")
|
|
await engine.dispose()
|
|
|
|
app = FastAPI(
|
|
title=settings.PROJECT_NAME,
|
|
version=settings.VERSION,
|
|
lifespan=lifespan,
|
|
docs_url="/docs" if settings.DEBUG or settings.ENVIRONMENT != "production" else None,
|
|
)
|
|
|
|
# CORS 配置
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.CORS_ORIGINS,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册 API 路由
|
|
app.include_router(api_router, prefix="/api")
|
|
app.include_router(kline_router, prefix="/api")
|
|
|
|
# WebSocket 实时订阅端点
|
|
@app.websocket("/ws/market/{market_address}")
|
|
async def websocket_market_endpoint(websocket: WebSocket, market_address: str):
|
|
channel = f"market:{market_address.lower()}"
|
|
await ws_manager.connect(websocket, channel)
|
|
try:
|
|
while True:
|
|
data = await websocket.receive_text()
|
|
# 客户端心跳 ping/pong
|
|
if data == "ping":
|
|
await websocket.send_text("pong")
|
|
except WebSocketDisconnect:
|
|
ws_manager.disconnect(websocket, channel)
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "ok", "version": settings.VERSION, "env": settings.ENVIRONMENT}
|