server.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import sys,os
  2. current_path = os.getcwd()
  3. sys.path.append(current_path+"\\web")
  4. import json
  5. from fastapi import FastAPI
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from router.graph_router import graph_router
  8. def save_api_spec(app: FastAPI):
  9. """
  10. 保存 FastAPI 应用的 OpenAPI 规范到文件中。
  11. """
  12. from fastapi.openapi.utils import get_openapi
  13. import yaml
  14. openapi_schema = get_openapi(
  15. title="FastAPI - Swagger UI",
  16. version="1.0.0",
  17. routes=app.routes
  18. )
  19. # 将 JSON 转换为 YAML
  20. yaml_data = yaml.dump(openapi_schema, sort_keys=False)
  21. # 保存为 YAML 文件
  22. with open("openapi.yaml", "w") as f:
  23. f.write(yaml_data)
  24. print("OpenAPI YAML 文件已生成:openapi.yaml")
  25. app = FastAPI()
  26. # 允许所有来源的跨域请求
  27. app.add_middleware(
  28. CORSMiddleware,
  29. allow_origins=["*"],
  30. allow_credentials=True,
  31. allow_methods=["*"],
  32. allow_headers=["*"],
  33. )
  34. app.include_router(graph_router)
  35. #app.include_router(dify_kb_router)
  36. save_api_spec(app)