flask-restful with flask-auth :具有不同身份验证的多个 HTTP 方法

flask-restful with flask-auth :multiple HTTP method with different authentication

我正在尝试使用具有多个 HTTP(GET、POST、PUT、DELETE)方法的相同 url,并且对于每个方法,它使用 flask-auth 进行不同的身份验证。

我尝试创建了超过 class 个

class GetUser(Resource):


    decorators = [Users.auth.login_required]
    def get(self):
        '''..etc'''

class PostUser(Resource):


    decorators = [Admin.auth.login_required]
    def post(self):
        '''..etc'''

restful_api.add_resource(GetUser,'/User')
restful_api.add_resource(PostUser,'/User')

但是发生的事情是 restful_api.add_resource(PostUser,'/User') 将覆盖 restful_api.add_resource(GetUser,'/User')

我能看到的唯一合理的选择是您创建 Flask-RESTful 的 Resource class 的子 class 并自己实现每个方法的装饰器.然后你的资源可以从你的 class 继承来拥有这个功能。

在您的 Resource subclass 中,您需要提供 dispatch_request 方法的替代实现:https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L543.

处理装饰器的代码是这样的:

    for decorator in self.method_decorators:
        meth = decorator(meth)

我想你可以将 method_decorators 更改为字典,然后按如下方式应用装饰器:

    for decorator in self.method_decorators[request.method.lower()]:
        meth = decorator(meth)

那么你上面的例子就变成了:

class User(MyResource):
    method_decorators = {
        'get': [Users.auth.login_required],
        'post': [Admin.auth.login_required]
    }

    def get(self):
        '''..etc'''

    def post(self):
        '''..etc'''

restful_api.add_resource(User,'/User')

我发现我也可以做到这一点

class User(Resource):


    @Admin.auth.login_required
    def post(self):
        '''..etc'''
    @Users.auth.login_required
    def get(self):
        '''..etc'''