问题描述
我正在尝试将 FastAPI 作为 Windows 服务运行。找不到任何文档或任何文章来将 Uvicorn 作为 Window 服务运行。 我也尝试使用 NSSM,但我的 Windows 服务停止了。
解决方法
我设法使用 uvicorn 作为 Windows 服务使用 NSSM 运行 FastAPI。
我必须deploy uvicorn programatically,基本上直接从您的 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
command
nssm.exe install "FastAPIWindowsService" "C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe" "C:\Scripts\FastAPIWindowsService\src\main.py"
相应地更改您的服务名称、python.exe 的路径和脚本的路径。安装后,您的服务应显示在 Windows 服务管理器中。
希望这对您有所帮助,并且对您有用!