docs.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from typing import Annotated
  2. from starlette.responses import HTMLResponse
  3. from typing_extensions import Doc
  4. def get_custom_ui_html(
  5. *,
  6. openapi_url: Annotated[
  7. str,
  8. Doc(
  9. """
  10. The OpenAPI URL that Swagger UI should load and use.
  11. This is normally done automatically by FastAPI using the default URL
  12. `/openapi.json`.
  13. """
  14. ),
  15. ],
  16. title: Annotated[
  17. str,
  18. Doc(
  19. """
  20. The HTML `<title>` content, normally shown in the browser tab.
  21. """
  22. ),
  23. ],
  24. swagger_js_url: Annotated[
  25. str,
  26. Doc(
  27. """
  28. The URL to use to load the Swagger UI JavaScript.
  29. It is normally set to a CDN URL.
  30. """
  31. ),
  32. ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
  33. swagger_css_url: Annotated[
  34. str,
  35. Doc(
  36. """
  37. The URL to use to load the Swagger UI CSS.
  38. It is normally set to a CDN URL.
  39. """
  40. ),
  41. ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
  42. swagger_favicon_url: Annotated[
  43. str,
  44. Doc(
  45. """
  46. The URL of the favicon to use. It is normally shown in the browser tab.
  47. """
  48. ),
  49. ] = "https://fastapi.tiangolo.com/img/favicon.png",
  50. ) -> HTMLResponse:
  51. """
  52. 生成加载 Swagger UI 的 HTML 页面(与 FastAPI 默认 `/docs` 行为一致,可自定义静态资源 URL)。
  53. 参数:
  54. - openapi_url (str): OpenAPI JSON 地址。
  55. - title (str): 页面标题。
  56. - swagger_js_url (str): Swagger UI JS 地址。
  57. - swagger_css_url (str): Swagger UI CSS 地址。
  58. - swagger_favicon_url (str): 站点图标地址。
  59. 返回:
  60. - HTMLResponse: 可直接返回给浏览器的 HTML 响应。
  61. """
  62. html = f"""
  63. <!DOCTYPE html>
  64. <html>
  65. <head>
  66. <link type="text/css" rel="stylesheet" href="{swagger_css_url}">
  67. <link rel="shortcut icon" href="{swagger_favicon_url}">
  68. <title>{title}</title>
  69. </head>
  70. <body>
  71. <div id="swagger-ui"></div>
  72. <script src="{swagger_js_url}"></script>
  73. <script>
  74. ui.configure({{url: '{openapi_url}'}});
  75. ui.initialize();
  76. </script>
  77. </body>
  78. </html>
  79. """
  80. return HTMLResponse(html)