Reputation: 1498
i'm trying to have same url that have multiple HTTP (GET,POST,PUT,DELETE) method and for each method it has different authentication using flask-auth.
i tried creating more than class like
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')
but what happend is that restful_api.add_resource(PostUser,'/User')
will override restful_api.add_resource(GetUser,'/User')
Upvotes: 3
Views: 1701
Reputation: 1498
i found out i could do this also
class User(Resource):
@Admin.auth.login_required
def post(self):
'''..etc'''
@Users.auth.login_required
def get(self):
'''..etc'''
Upvotes: 3
Reputation: 67479
The only reasonable option I can see is that you create a subclass of Flask-RESTful's Resource
class and implement per-method decorators yourself. Then your resources can inherit from your class to have this functionality.
In your Resource
subclass, you will need to provide an alternative implementation of the dispatch_request
method: https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L543.
The code that handles decorators is this:
for decorator in self.method_decorators:
meth = decorator(meth)
I guess you can change the method_decorators
to a dictionary, and then apply the decorators as follows:
for decorator in self.method_decorators[request.method.lower()]:
meth = decorator(meth)
Then your example above becomes:
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')
Upvotes: 6