dockerfile 中的 uvicorn 命令和 pythonfile 中的 运行 fastapi 有区别吗?

is there a difference between running fastapi from uvicorn command in dockerfile and from pythonfile?

我正在 运行快速 api 开发时,我的 app.py 文件中有以下代码

app.py中的代码:

import uvicorn


if __name__=="__main__":
    uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)

所以我正要 运行 CMD ["python3","app.py"] 在我的 Dockerfile 中。

在快速 api 示例中,他们做了这样的事情:

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

我想知道这两种方法有什么区别,因为我认为它们都可以。

答案是。应用程序没有区别,使用 Docker 进行部署只是使其 更容易 ,没有 Docker 您需要 运行 它与 ASGI 兼容的服务器,如 Uvicorn,您可能还需要设置一些工具以确保它在停止或崩溃时自动重新启动。 Docker 图像可以自动处理所有这些工作,而不是尝试手动处理。

不,没有区别

命令行 运行 方法 (uvicorn app.main:app) 和使用 python 命令 (python app.py) 执行 app.py 是相同的。这两种方法都在后台调用 uvicorn.main.run(...) 函数。

换句话说,uvicorn命令是uvicorn.run(...)快捷方式 ]函数。

所以,在你的例子中函数调用

uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)

可以通过 uvicorn 命令行完成,

uvicorn app.app:app --host 0.0.0.0 --port 4557 --reload --debug --workers 3

旁注

--debug 选项在 command line options help page, but it can be found in the source code 中隐藏。因此,感觉使用 uvicorn 命令 运行 应用程序可以被视为 产品。