main.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. # 打印启动配置
  31. print("="*50)
  32. print("Tolan 后端服务启动")
  33. print("="*50)
  34. print(f"主机: {settings.HOST}")
  35. print(f"端口: {settings.PORT}")
  36. # SSL证书路径配置
  37. # 优先使用环境变量配置的证书路径(生产环境)
  38. ssl_keyfile = settings.SSL_KEYFILE
  39. ssl_certfile = settings.SSL_CERTFILE
  40. # 如果环境变量未配置,使用本地开发证书
  41. if not ssl_keyfile or not ssl_certfile:
  42. ssl_dir = Path(__file__).parent.parent / "ssl"
  43. ssl_keyfile = str(ssl_dir / "key.pem")
  44. ssl_certfile = str(ssl_dir / "cert.pem")
  45. # 检查证书是否存在
  46. if ssl_keyfile and ssl_certfile:
  47. if not os.path.exists(ssl_keyfile) or not os.path.exists(ssl_certfile):
  48. print(f"⚠️ SSL证书不存在")
  49. print(f" 证书: {ssl_certfile}")
  50. print(f" 私钥: {ssl_keyfile}")
  51. print(" 将以HTTP模式启动")
  52. ssl_keyfile = None
  53. ssl_certfile = None
  54. else:
  55. print(f"✅ 使用SSL证书:")
  56. print(f" 证书: {ssl_certfile}")
  57. print(f" 私钥: {ssl_keyfile}")
  58. # 显示访问地址
  59. protocol = "https" if ssl_keyfile and ssl_certfile else "http"
  60. ws_protocol = "wss" if ssl_keyfile and ssl_certfile else "ws"
  61. print(f"\n访问地址:")
  62. print(f" HTTP: {protocol}://{settings.HOST}:{settings.PORT}")
  63. print(f" WebSocket: {ws_protocol}://{settings.HOST}:{settings.PORT}/ws")
  64. print("="*50 + "\n")
  65. uvicorn.run(
  66. "main:app",
  67. host=settings.host,
  68. port=settings.port,
  69. reload=True,
  70. ssl_keyfile=ssl_keyfile,
  71. ssl_certfile=ssl_certfile,
  72. )