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

Ham*_*daq 3 authentication flask python-2.7 flask-restful flask-httpauth

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

我尝试创建的不仅仅是类

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')
Run Code Online (Sandbox Code Playgroud)

但是会发生什么事情restful_api.add_resource(PostUser,'/User')会覆盖restful_api.add_resource(GetUser,'/User')

Mig*_*uel 6

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

在你的Resource子类,你需要提供一个替代实现的dispatch_request方法:https://github.com/flask-restful/flask-restful/blob/master/flask_restful/ 初始化的.py#L543.

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

    for decorator in self.method_decorators:
        meth = decorator(meth)
Run Code Online (Sandbox Code Playgroud)

我想你可以把它改成method_decorators一个字典,然后按如下方式应用装饰器:

    for decorator in self.method_decorators[request.method.lower()]:
        meth = decorator(meth)
Run Code Online (Sandbox Code Playgroud)

然后你上面的例子变成:

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')
Run Code Online (Sandbox Code Playgroud)