用Nuitka将Fastapi应用打包成exe
main.py内容如下:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
if __name__=='__main__':
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
在main.py所在目录中打开命令行窗口,执行如下Nuitka打包命令:
python -m nuitka --standalone --mingw64 --show-memory --show-progress --nofollow-imports --include-package=uvicorn --include-package=click --include-package=h11 --include-package=starlette --include-package=fastapi --output-dir=o main.py
等待几分钟,即可打包完成。打包后会生成o/main.dist 目录,双击此目录下的main.exe即可启动FastAPI服务。服务启动后,在浏览器访问http://localhost:8000/,可查看到响应字符串
{"Hello":"World"}