使用 uvicorn.run 启动服务时,FastAPI 服务结果为 404

FastAPI Service Results in 404 when service is started using uvicorn.run

FastAPI 和 uvicorn 的新手,但我想知道为什么当我 运行 我的“hello world”服务通过从命令行使用 uvicorn 启动它时,它工作正常,但是当使用“uvicorn.run" 服务内部的方法,服务启动,但是当我发送 GET 时,我总是收到 404,响应主体为 {"detail": "Not Found"}?

这是我的代码:

import uvicorn
from fastapi import FastAPI

app = FastAPI()
uvicorn.run(app, host="127.0.0.1", port=5049)


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

那总是 returns 与 404 如下:

# curl http://127.0.0.1:5049/
{"detail":"Not Found"}

我的服务输出显示:

INFO:     Started server process [28612]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:5049 (Press CTRL+C to quit)
INFO:     127.0.0.1:55446 - "GET / HTTP/1.1" 404 Not Found

如果我注释掉“uvicorn.run”行,然后使用 (运行ning on Windows 10):

从命令行启动服务
uvicorn.exe test:app --host=127.0.0.1 --port=5049

我得到正确的回复:

# curl http://127.0.0.1:5049/
{"message":"Hello World"}

因为,语句uvicorn.run(app, host="127.0.0.1", port=5049)是在root(...)[=之前执行的26=] 函数并且执行永远不会到达 root(...) 函数。

但是,当您使用命令行 运行 应用程序时,应用程序会以 lazy 方式加载,并且因此 root(...) 函数正在执行。

像这样肯定可以解决问题,

import uvicorn
from fastapi import FastAPI

app = FastAPI()


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


<b> # at last, the bottom of the file/module
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=5049)</b>