【问题标题】:Fastapi returns 404 when accessing URL in the browserFastapi 在浏览器中访问 URL 时返回 404
【发布时间】:2021-10-02 13:20:06
【问题描述】:

我正在学习 fastapi 并创建了以下示例应用程序

from fastapi import FastAPI
import uvicorn
app = FastAPI()

@app.get("/hello")
async def hello_world():
   return {"message": "hello_world"}

if __name__== "__main__":
   uvicorn.run(app, host="127.0.0.1", port=8080)

服务器启动正常,但是当我在浏览器中测试url 时出现以下错误:

{"detail": "Not Found"}

日志中有这个错误:

"GET / HTTP /" 404 Not Found

我注意到另一个奇怪的问题,当我犯了一些错误时,它没有检测到错误并且仍在启动服务器。例如,如果我像下面这样更改函数

@app.get("/hello")
async def hello_world():
   print (sample)
   return {"message": "hello_world"}

它应该抛出错误NameError: "sample" not defined,但它仍在启动服务器。任何建议都会有所帮助

【问题讨论】:

  • 响应 {"detail": "Not Found"} 是有效的,因为您访问了 URL /(根 URL),但在您的应用中,您没有任何路线可以提供相同的服务。在这种情况下,您必须访问/hello 路径。第二个错误在 Python 中很明显,因为您没有在程序上下文中定义任何名为 sample 的变量。
  • 由于您的第二个示例中的代码从未运行(您从未如您的问题中所述调用/hello),因此永远不会将其检测为不存在。变量在实际需要之前不会被解析。

标签: python api fastapi uvicorn


【解决方案1】:

问题一:

因为它不起作用。

您为路径/hello 编写了一个处理程序。但是您正在测试未配置的路径/。


对于问题 2:您没有定义变量 sample。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2016-07-23
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多