main.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. import socket
  30. from pathlib import Path
  31. # 🔥 DNS预解析(减少首次连接延迟)
  32. print("🔧 预解析DNS...")
  33. try:
  34. socket.getaddrinfo('dashscope.aliyuncs.com', 443)
  35. print("✅ DNS预解析完成\n")
  36. except Exception as e:
  37. print(f"⚠️ DNS预解析失败(不影响正常使用): {e}\n")
  38. # 打印启动配置
  39. print("="*50)
  40. print("Tolan 后端服务启动")
  41. print("="*50)
  42. print(f"主机: {settings.HOST}")
  43. print(f"端口: {settings.PORT}")
  44. # SSL证书路径配置
  45. # 优先使用环境变量配置的证书路径(生产环境)
  46. ssl_keyfile = settings.SSL_KEYFILE
  47. ssl_certfile = settings.SSL_CERTFILE
  48. # 如果环境变量未配置,使用本地开发证书
  49. if not ssl_keyfile or not ssl_certfile:
  50. ssl_dir = Path(__file__).parent.parent / "ssl"
  51. ssl_keyfile = str(ssl_dir / "key.pem")
  52. ssl_certfile = str(ssl_dir / "cert.pem")
  53. # 检查证书是否存在
  54. if ssl_keyfile and ssl_certfile:
  55. if not os.path.exists(ssl_keyfile) or not os.path.exists(ssl_certfile):
  56. print(f"⚠️ SSL证书不存在")
  57. print(f" 证书: {ssl_certfile}")
  58. print(f" 私钥: {ssl_keyfile}")
  59. print(" 将以HTTP模式启动")
  60. ssl_keyfile = None
  61. ssl_certfile = None
  62. else:
  63. print(f"✅ 使用SSL证书:")
  64. print(f" 证书: {ssl_certfile}")
  65. print(f" 私钥: {ssl_keyfile}")
  66. # 显示访问地址
  67. protocol = "https" if ssl_keyfile and ssl_certfile else "http"
  68. ws_protocol = "wss" if ssl_keyfile and ssl_certfile else "ws"
  69. print(f"\n访问地址:")
  70. print(f" HTTP: {protocol}://{settings.HOST}:{settings.PORT}")
  71. print(f" WebSocket: {ws_protocol}://{settings.HOST}:{settings.PORT}/ws")
  72. print("="*50 + "\n")
  73. uvicorn.run(
  74. "main:app",
  75. host=settings.host,
  76. port=settings.port,
  77. reload=True,
  78. ssl_keyfile=ssl_keyfile,
  79. ssl_certfile=ssl_certfile,
  80. )