如何解决使用uvicorn.run启动服务时,FastAPI服务的结果为404
FastAPI和uvicorn的新手,但是我想知道为什么当我通过从命令行使用uvicorn启动它来运行“ hello world”服务时,它可以正常工作,但是当从内部使用“ uvicorn.run”方法时我的服务会启动该服务,但是当我发送GET时,我总是会收到一个带有{“ detail”:“ Not Found”}}响应正文的404?
这是我的代码:
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"}
解决方法
因为,语句 uvicorn.run(app,host="127.0.0.1",port=5049)
在 root(...)
函数之前执行,并且执行从未达到root(...)
函数。
但是,当您使用命令行运行应用程序时,该应用程序以 lazy 的方式加载,因此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,port=5049)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。