python - 将自定义 javascript 添加到 Python 中的 FastAPI Swagger UI 文档网页

标签 python fastapi swagger-ui

我想将自定义 javascript 文件或代码加载到 FastAPI Swagger UI 网页,以便在创建 FastAPI 对象时添加一些动态交互。

例如,我想在文档网页上的 Swagger UI 中

<script src="custom_script.js"></script> 

<script> alert('worked!') </script>

我试过:

api = FastAPI(docs_url=None)

api.mount("/static", StaticFiles(directory="static"), name="static")

@api.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=api.openapi_url,
        title=api.title + " - Swagger UI",
        oauth2_redirect_url=api.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/sample.js",
        swagger_css_url="/static/sample.css",
    )

但它不起作用。有没有一种方法可以使用 Python 在 FastAPI Swagger UI 的文档网页上插入我的自定义 javascript 代码?

最佳答案

终于成功了。这就是我所做的:

from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles

api = FastAPI(docs_url=None) 

path_to_static = os.path.join(os.path.dirname(__file__), 'static')
logger.info(f"path_to_static: {path_to_static}")
api.mount("/static", StaticFiles(directory=path_to_static), name="static")

@api.get("/docs", include_in_schema=False)
        async def custom_swagger_ui_html():
            return get_swagger_ui_html(
                openapi_url=api.openapi_url,
                title="My API",
                oauth2_redirect_url=api.swagger_ui_oauth2_redirect_url,
                swagger_js_url="/static/custom_script.js",
                # swagger_css_url="/static/swagger-ui.css",
                # swagger_favicon_url="/static/favicon-32x32.png",
            )

重要提示:

  1. 确保静态路径正确并且所有文件都在静态文件夹中,默认情况下静态文件夹应与创建 FastAPI 对象的脚本位于同一文件夹中。

例如:

 -parent_folder
     Build_FastAPI.py
     -static_folder
         custom_script.js
         custom_css.css
  1. 找到 swagger-ui-bundle.js在互联网上并将其所有内容复制粘贴到 custom_script.js,然后在 custom_script.js 的开头或结尾添加您的自定义 javascript 代码。

例如:

setTimeout(function(){alert('My custom script is working!')}, 5000);
...
.....
/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */
            !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}
...
.....
  1. 保存并刷新浏览器,一切顺利!

如果有人知道更好的答案,欢迎您,最好的答案将被接受!

关于python - 将自定义 javascript 添加到 Python 中的 FastAPI Swagger UI 文档网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74661044/

相关文章:

node.js - node.js 上 Swagger 的可空字段

json - swagger api如何添加常用参数

python - ASGI 'lifespan' 协议(protocol)似乎不受支持

Python/Tkinter : Are Tkinter StringVar (IntVar, 等)线程安全吗?

python - 处理请求时发生异常

python - 如何告诉 python 不要打印列表中的项目?

python - Fastapi 中的 Flask 拆卸请求等效项

python - 使用 pdfkit 和 FastAPI 下载 PDF 文件

带有 Swagger 文档的 Grails 3.1.4 项目

python - discord.py 上是否有用于用户名更改的事件处理程序?