如何使用FastAPI
请查看fastAPI官网例子,说的很详细了,不在赘述
如何作为服务启动
例如你有一个main.py如下:
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 部署,你可以使用nssm install
nssm.exe install “FastAPIWindowsService” “C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe” “C:\Scripts\FastAPIWindowsService\src\main.py”
更详细的NSS指令请参考NSSM指令文档
NSSM参考示例
我写了一个bat文件,特别注意的是当指定App的log信息文件位置时,确保目录存在
@setlocal enableextensions
@echo off
@cd /d "%~dp0"
REM file directory
set cwd=%~dp0%
md log
REM Uninstall old services
nssm stop helloService
nssm remove helloService confirm
pip install fastapi
pip install uvicorn
nssm.exe install "helloService" "C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python39\python.exe" "%cwd%__pycache__\main.cpython-39.pyc"
nssm set helloService Start SERVICE_AUTO_START
nssm set helloService DisplayName "helloService"
::nssm set helloService AppParameters "-TCPport 9000"
nssm set helloService AppStdout "%cwd%\stdout.log"
nssm set helloService AppStderr "%cwd%\stderr.log"
REM Start services
nssm start FeaturePointService
windows 删除服务
管理员权限启动命令行输入:sc delete FeaturePointService
参考文档
FastAPI as a Windows service
How to fix SERVICE_PAUSED error on starting nssm server
windows delete service