如何从诗歌运行FastAPI应用程序?

问题描述

我有一个通过诗歌构建的fastapi项目。我想使用pyproject.tom中的脚本部分运行应用程序,如下所示:

poetry run start

该部分的双引号里面是什么?

[tool.poetry.scripts]
start = ""

我试图运行以下脚本。

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

def main():
    print("Hello World")
    uvicorn.run(app,host="0.0.0.0",port=8000,reload=True,workers=2)

if __name__ == "__main__":
    main()

它将停止应用程序,并仅显示这样的警告。

警告:您必须将应用程序作为导入字符串传递才能启用“重新加载”或“工人”。

解决方法

我找到了解决这个问题的方法。见下文:

pyproject.toml

[tool.poetry.scripts]
start = "my_package.main:start"

在您的 main.py 内的 my_package 文件夹中。

import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

def start():
    """Launched with `poetry run start` at root level"""
    uvicorn.run("my_package.main:app",host="0.0.0.0",port=8000,reload=True)
,

您将需要传递模块路径(module:function):

[tool.poetry.scripts]
start = "app:main"

现在运行以下命令将在main模块中调用app函数:

$ poetry run start
,

就像错误消息中所说的那样,做

uvicorn.run("app")

请注意,也使用reload和worker是没有用的,只会使用reloader。这些标志是互斥的

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...