| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- """
- 主应用入口
- """
- from fastapi import FastAPI, WebSocket
- from fastapi.middleware.cors import CORSMiddleware
- from config import settings
- from websocket_handler import WebSocketHandler
- app = FastAPI(title="Tolan Backend API")
- # 配置CORS
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"], # 生产环境应该限制具体域名
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- @app.get("/")
- async def root():
- """健康检查"""
- return {"status": "ok", "message": "Tolan Backend API"}
- @app.websocket("/ws")
- async def websocket_endpoint(websocket: WebSocket):
- """WebSocket端点"""
- handler = WebSocketHandler(websocket)
- await handler.handle_connection()
- if __name__ == "__main__":
- import uvicorn
- import os
- from pathlib import Path
-
- # SSL证书路径
- ssl_dir = Path(__file__).parent.parent / "ssl"
- ssl_keyfile = str(ssl_dir / "key.pem")
- ssl_certfile = str(ssl_dir / "cert.pem")
-
- # 检查证书是否存在
- if not os.path.exists(ssl_keyfile) or not os.path.exists(ssl_certfile):
- print(f"警告: SSL证书不存在,请检查 {ssl_dir} 目录")
- ssl_keyfile = None
- ssl_certfile = None
-
- uvicorn.run(
- "main:app",
- host=settings.host,
- port=settings.port,
- reload=True,
- ssl_keyfile=ssl_keyfile,
- ssl_certfile=ssl_certfile,
- )
|