【发布时间】: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