首页 > 解决方案 > 使用 uvicorn.run 启动服务时,FastAPI 服务结果为 404

问题描述

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"}

总是返回 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”行,然后从命令行启动服务(在 Windows 10 上运行):

uvicorn.exe test:app --host=127.0.0.1 --port=5049

我得到正确的回应:

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

标签: python-3.xfastapiuvicorn

解决方案


因为,语句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)

推荐阅读