【问题标题】:Flask-RESTful specify HTTP methods allowed for specific endpointsFlask-RESTful 指定特定端点允许的 HTTP 方法
【发布时间】:2020-05-14 01:47:22
【问题描述】:

假设我有两个 Resource 类:

class UserView(Resource):
    def get(self, id):
        ...
    def post(self):
        ...
    def put(self, id):
        ...
    def delete(self, id):
        ...


class AnotherUserView(Resource):
    def get(self):
        ...
    def put(self):
        ...
    def delete(self):
        ...


api.add_resource(UserView, '/user/<int:id>')
api.add_resource(AnotherUserView, '/user')

鉴于上面的代码,UserViewGETPUTDELETE 方法都需要一个路径参数id。因此,UserView 映射到路由/user/&lt;int:id&gt;。但是POST方法不需要路径参数id而是包含在提供参数id的路由下,会造成混淆。

所以现在,我正在考虑是否有一种方法可以指定在特定路由(或端点)中允许哪些方法,就像我们可以用 Flask:@app.route('/user/&lt;int:id&gt;', methods=['GET', 'PUT', 'DELETE'] 做的那样。

预期我能做什么:

api.add_resource(UserView, '/user/<int:id>', methods=['GET', 'PUT', 'DELETE'])
api.add_resource(UserView, '/user', methods=['POST'])
api.add_resource(AnotherUserView, '/user', methods=['GET', 'PUT', 'DELETE'])

但这实际上是行不通的,因为编译器告诉我我正在覆盖视图函数UserView

我阅读了Flask-RESTful 的文档,发现api.add_resource 没有methods 的参数,可以像app.route 那样用于指定允许的HTTP 方法。有没有办法做到这一点?

【问题讨论】:

    标签: rest flask flask-restful http-method


    【解决方案1】:

    在 Flask-Restful 中,类函数 getpost 等对应于 http 方法。如果您不想为 Resource 使用特定方法,只需将其省略即可。

    我个人并不觉得在类中没有 id 的 POST 方法令人困惑。

    要获得您的预期结果,请考虑为每个资源添加所需的路线。例如

    from flask_restful import Api, Resource
    
    class User(Resource):
        def get(self, id=None):
            if id:
                return "specific user"
            else:
                return "list of users"
    
        def post(self):
            return "post with no id!"
    
        def delete(self, id=None):
            if id:
                return "deleting user"
            else:
                return "need to specify a user"
    
    api.add_resource(User, '/user', '/user/<int:id>')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2016-09-06
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多