我正在尝试将 FastAPI 作为 Windows 服务运行。找不到任何文档或任何文章来将 Uvicorn 作为 Windows 服务运行。 我也尝试使用 NSSM,但我的 Windows 服务停止了。
我设法使用 NSSM 将 uvicorn 作为 Windows 服务来运行 FastAPI。
我必须 以编程方式部署 uvicorn,基本上直接从您的 Python 脚本运行 uvicorn,然后使用 NSSM 创建并安装自定义服务。
这是一个基于 FastAPI 的 example 的小示例,但不是使用命令行中的
uvicorn main:app --reload
运行它,而是使用您自己的配置添加 uvicorn.run(app, **config)
。
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")
然后您可以使用标准
nssm install
命令与NSSM一起安装它
nssm.exe install "FastAPIWindowsService" "C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe" "C:\Scripts\FastAPIWindowsService\src\main.py"
相应地更改您的服务名称、python.exe 的路径和脚本的路径。安装后,您的服务应出现在 Windows 服务管理器中。
希望这对您有所帮助,对您有用!
扩展一下另一个答案,有几种不同的方法可以将 FastAPI 作为 Windows 服务运行(概括为能够将任何 Python 应用程序作为 Windows 服务运行)。我发现的最常见的方法是:
在尝试了其中的一些之后,我发现 NSSM 是迄今为止最简单和最有效的方法。基本步骤如下:
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8000, workers=4)
如果 Windows 机器上没有 Python,请安装它。同时下载 nssm.exe
通过运行
py main.py
在 Windows 机器上测试您的应用程序。如果它启动并运行,那么您就可以部署为 Windows 服务。
使用 nssm 创建服务:
nssm install <windows service name> <python.exe path> main.py
nssm set <windows service name> AppDirectory <root directory of app>
.nssm set <windows service name> Description <app description>
.nssm start <windows service name>
如果一切顺利,那么它应该启动并运行。上面的其他一些评论者在应用程序启动时遇到问题,这可能是因为未设置 AppDirectory,因此无法找到文件。祝你好运!