使用 uvicorn.run 启动 FastAPI 应用程序时会导致 404 错误响应

Gre*_*egH 18 http-status-code-404 python-3.x fastapi uvicorn

FastAPI 和 uvicorn 的新手,但我想知道为什么当我通过从命令行使用 uvicorn 启动它来运行我的“hello world”服务时,它工作正常,但是当从我的服务内部使用“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"}
Run Code Online (Sandbox Code Playgroud)

总是返回 404,如下所示:

# curl http://127.0.0.1:5049/
{"detail":"Not Found"}
Run Code Online (Sandbox Code Playgroud)

我的服务的输出显示:

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
Run Code Online (Sandbox Code Playgroud)

如果我注释掉“uvicorn.run”行,然后从命令行启动该服务(在 Windows 10 上运行):

uvicorn.exe test:app --host=127.0.0.1 --port=5049
Run Code Online (Sandbox Code Playgroud)

我得到正确的回应:

# curl http://127.0.0.1:5049/
{"message":"Hello World"}
Run Code Online (Sandbox Code Playgroud)

JPG*_*JPG 17

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

但是,当您使用命令行运行应用程序时,应用程序会以惰性方式加载,因此该root(...)函数会被执行。

像这样的事情肯定会解决这个问题:

import uvicorn
from fastapi import FastAPI

app = FastAPI()


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


 # at last, the bottom of the file/module
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=5049)
Run Code Online (Sandbox Code Playgroud)