Fastapi笔记

1.安装fastapi:

pip install fastapi

安装uvicorn来作为服务器:

pip install uvicorn[standard]

###注意事项:

在使用pip安装uvicorn服务时需要确定pip对应的python版本和$PATH默认路径是否一致,如果不一致会出现报错:bash: uvicorn: command not found

这种情况是因为在环境变量中找到的python版本和pip对应的python版本不一致,导致找不到pip安装的库,需要将对应版本的python路径配置在环境变量中:

export PATH=$PATH:/usr/local/python3/bin

2.开启服务:

uvicorn main:app --host='0.0.0.0' --reload

默认端口是8000,由于使用docker运行,需要将端口映射出来,在这里如果不配置--host默认为“127.0.0.1”,局域网内也是会出现访问不到。

###遇到的问题:内网中访问静态文档http://内网地址:端口号/docs为空。

###解决方案:添加swagger-ui

(1)下载swagger-ui包(官网:Release Swagger UI v4.1.3 Released! · swagger-api/swagger-ui (github.com));

(2)将包中的地址挂载在/static位置:

from fastapi.staticfiles import StaticFiles
app.mount("/static",StaticFiles(directory="/mnt/mnt/users/jiao/fastapi/study/swagger-ui/dist"),name="static"),

(3)配置fastapi(/usr/local/python3/lib/python3.7/site-packages/fastapi/openapi/docs.py),具体位置根据自己安装fastapi的位置,可以通过pip查看(pip show fastapi):

def get_swagger_ui_html(
    *,
    openapi_url: str,
    title: str,
    swagger_js_url: str = "/static/swagger-ui-bundle.js",
    swagger_css_url: str = "/static/swagger-ui.css",
    swagger_favicon_url: str = "/static/favicon-32x32.png",
    oauth2_redirect_url: Optional[str] = None,
    init_oauth: Optional[Dict[str, Any]] = None,
) -> HTMLResponse:

(4)刷新页面http://内网地址:端口号/docs:

猜你喜欢

转载自blog.csdn.net/SecretGirl/article/details/121979993