python - resource 可选参数,用于检索 Flask Restful 上的所有数据

标签 python rest flask flask-restful

我想了解 Flask-RESTful,但我不知道如何为资源提供可选参数。

即:

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>')

在上面的例子中,如何创建一个新的端点来返回所有的待办事项,而不仅仅是一个?

取自:https://flask-restful.readthedocs.io/en/0.3.5/quickstart.html

最佳答案

我认为最好的方法是拥有两个资源/端点。第一个管理集合(获取待办事项列表,添加新的待办事项),第二个管理集合的项目(更新或删除项目):

class TodoListResource(Resource):
    def get(self):
        return {'todos': todos}


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

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


api.add_resource(TodoListResource, '/todos')
api.add_resource(TodoResource, '/todos/<string:todo_id>/')

这种方式更加 REST。

关于python - resource 可选参数,用于检索 Flask Restful 上的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384907/

相关文章:

python - 获取有关数据类字段的类型信息

Python:在 Unicode 转义字符串上使用 .format()

java - 如何为 feign bean 字段设置 JsonProperty 名称

rest - Twitter API *真的*是 RESTful 吗?

python - Flask SQLalchemy - 多对多 - 显示带有所有标签的照片(或带有所有帖子的博客等)

python - Python 3.5.2-Windows上的Flask 0.12-无法创建一致的方法解析顺序

python - 如何通过 subprocess.Popen 将 utf8 字符串从 python 正确传递到 hunspell?

python - 如何在 PySpark 中的每个分区中回填空值

php - 新的 Bing API PHP 示例不起作用

python - 使用Flask-Elasticsearch配置Elasticsearch索引存储的路径