python-3.x - 使用 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"}
解决方案
因为,语句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)
推荐阅读
- arrays - 将字符串数组转换为字符串数组
- javascript - 如何到达强框
- javascript - core.js:6210 错误类型错误:this.service.addDepartment 不是函数
- android - 色盲的颜色校正/过滤器
- reactjs - 窗口上的 TypeScript mousemove 事件
- python - 如何解决 __init__() 缺少 4 个必需的位置参数:“姓名”、“电子邮件”、“密码”和“年龄”
- postgresql - 插入后无法检索任何关系表
- google-sheets - Arrayformula 计算最后 N 个元素的平均值
- c - 如何快速从 OpenSSL 的 RIPEMD160 中获取 HASH
- sas - 需要帮助解决 SAS 问题以根据条件数据创建新变量