main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. 主应用入口
  3. """
  4. from fastapi import FastAPI, WebSocket
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from config import settings
  7. from websocket_handler import WebSocketHandler
  8. app = FastAPI(title="Tolan Backend API")
  9. # 配置CORS
  10. app.add_middleware(
  11. CORSMiddleware,
  12. allow_origins=["*"], # 生产环境应该限制具体域名
  13. allow_credentials=True,
  14. allow_methods=["*"],
  15. allow_headers=["*"],
  16. )
  17. @app.get("/")
  18. async def root():
  19. """健康检查"""
  20. return {"status": "ok", "message": "Tolan Backend API"}
  21. @app.websocket("/ws")
  22. async def websocket_endpoint(websocket: WebSocket):
  23. """WebSocket端点"""
  24. handler = WebSocketHandler(websocket)
  25. await handler.handle_connection()
  26. if __name__ == "__main__":
  27. import uvicorn
  28. import os
  29. from pathlib import Path
  30. # SSL证书路径
  31. ssl_dir = Path(__file__).parent.parent / "ssl"
  32. ssl_keyfile = str(ssl_dir / "key.pem")
  33. ssl_certfile = str(ssl_dir / "cert.pem")
  34. # 检查证书是否存在
  35. if not os.path.exists(ssl_keyfile) or not os.path.exists(ssl_certfile):
  36. print(f"警告: SSL证书不存在,请检查 {ssl_dir} 目录")
  37. ssl_keyfile = None
  38. ssl_certfile = None
  39. uvicorn.run(
  40. "main:app",
  41. host=settings.host,
  42. port=settings.port,
  43. reload=True,
  44. ssl_keyfile=ssl_keyfile,
  45. ssl_certfile=ssl_certfile,
  46. )