flask-restful : 在服务器上找不到请求的 URL

flask-restful : The requested URL was not found on the server

我正在尝试遵循 flask-restful 的文档并尝试 运行 以下代码。

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)

但是当我尝试使用“http://127.0.0.1:5000/todo1”URL 运行 它时,它会以消息 "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." 进行响应。我对代码做错了什么。请帮忙。

问题在于您为资源定义 url 路由的方式。现在您正在尝试通过 http://127.0.0.1:5000/todo1 访问它,但您已定义 TodoSimple 来处理发送到 http://127.0.0.1:5000/1 的请求。我建议将代码更改为如下所示

api.add_resource(TodoSimple, '/todo/<int:todo_id>')

然后,尝试通过 GET http://127.0.0.1:5000/todo/1

访问它