如何在FastAPI的Swagger UI中添加自定义HTML内容(如按钮)?
在FastAPI的Swagger UI中添加自定义授权按钮的问题
我需要在FastAPI应用的Swagger UI中添加一个自定义按钮。此前找到过可向Swagger UI添加自定义JavaScript的方案,搭配FastAPI官方文档的扩展OpenAPI方法可实现,但该方案仅支持JS代码。
我尝试添加仿Swagger UI授权按钮样式的HTML代码:
custom_html = '<div class="scheme-containerr"><section class="schemes wrapper block col-12"><div class="auth-wrapper"><button class="btn authorize"><span>Authorize Google</span><svg width="20" height="20"><use href="#unlocked" xlink:href="#unlocked"></use></svg></button></div></section></div>' @app.get("/docs", include_in_schema=False) async def custom_swagger_ui_html(): return get_swagger_ui_html( openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, swagger_js_url="/static/swagger-ui-bundle.js", swagger_css_url="/static/swagger-ui.css", custom_js_url=google_custom_button, custom_html=custom_html, ) def get_swagger_ui_html( *, ... custom_html: Optional[str] = None, ) -> HTMLResponse: ... html = f""" <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="{swagger_css_url}"> <link rel="shortcut icon" href="{swagger_favicon_url}"> <title>{title}</title> </head> <body> <div id="swagger-ui"> {custom_html if custom_html else ""} <!-- 我把HTML代码加在了这里 --> </div> """ ....
但发现放入<div id="swagger-ui"></div>内的内容会被覆盖,无法在Swagger UI中显示。若将自定义HTML代码放在该div外部,虽能显示按钮(如下图所示),但位置不符合需求,希望将按钮添加到原授权按钮所在的位置。

内容的提问来源于stack exchange,提问作者Ghasem
相关产品推荐
相关产品推荐

