我想将自定义 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",
)
重要提示:
- 确保静态路径正确并且所有文件都在静态文件夹中,默认情况下静态文件夹应与创建 FastAPI 对象的脚本位于同一文件夹中。
例如:
-parent_folder Build_FastAPI.py -static_folder custom_script.js custom_css.css
- 找到 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()}
...
.....
- 保存并刷新浏览器,一切顺利!
如果有人知道更好的答案,欢迎您,最好的答案将被接受!
关于python - 将自定义 javascript 添加到 Python 中的 FastAPI Swagger UI 文档网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74661044/