环境:openEuler、python 3.11.6、fastapi 0.115.2
背景:居家办公,默认搭建的fastapi的docs接口为空白
时间:20241016
说明:网上很多教程的缺点是复杂(但是能够了解的更清楚),使用官方文档解决很便利
官方文档地址:Custom Docs UI Static Assets
1、搭建环境
安装相应的python包
pip install fastapi uvicorn
创建main文件:
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/") 根路由
async def root():
return "I want to change the world"
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
启动命令:uvicorn main:app --reload --host 0.0.0.0 --port 8000
运行测试:
说明启动成功
(venv) [jack@Laptop-L14-gen4 fastTest]$ uvicorn main:app --reload --host 0.0.0.0 --port 8000
INFO: Will watch for changes in these directories: ['/home/jack/fastTest']
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started reloader process [6119] using StatReload
INFO: Started server process [6121]
INFO: Waiting for application startup.
INFO: Application startup complete.
浏览器查看
至此,说明基本环境搭建完毕
2、问题发现
默认访问 http://172.26.20.199:8000/docs 应该如下:
可问题却是空白
原因分析:
fastapi的文件是提供的CDN为国外的网址,偶尔可能存在网络延迟,导致为空白,使用F12可以看到是文件获取不到
3、解决问题
第一种方式的再试试,存在这种可能性
第二种方式为复制官方文档提供的部分代码:
增加的代码部分
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
app = FastAPI(docs_url=None, redoc_url=None)
@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="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
)
上述代码完全无脑复制到你的main.py中,覆盖app = 这一行即可,复制完如下:
main.py
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
app = FastAPI(docs_url=None, redoc_url=None)
@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="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
)
@app.get("/") 根路由
async def root():
return "I want to change the world"
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
启动命令:uvicorn main:app --reload --host 0.0.0.0 --port 8000
保存,fastapi会自动重新加载,刷新网页即可。