问题
I was wondering if there is any way that I can use a decorator just for some methods from my class, for example in the following code I want token_required
to decorate all methods excepting the POST, how could I possibly achieve that?
class UserAPI(MethodView):
def token_required(view_method):
@wraps(view_method)
def decorated(*args, **kwargs):
token = None
if 'token' in request.headers:
token = request.headers['token']
if not token:
return "no token"
return view_method(*args, **kwargs)
return decorated
decorators = [token_required]
def get(self, user_id):
if user_id is None:
# return a list of users
return "no user id"
else:
# expose a single user
return "user id"
def post(self):
# create a new user
return "create new user"
def delete(self, user_id):
# delete a single user
return "delete user id"
def put(self, user_id):
# update a single user
return "update user id"
回答1:
Here is a few ways.
1) Add condition on request method
into decorator
:
@wraps(view_method)
def decorated(*args, **kwargs):
if request.method == 'POST':
# skip token processing - just result of view method
return view_method(*args, **kwargs)
token = None # etc... (your code)
2) Сreate a universal decorator
for any point and use him without decorators
property.
from functools import wraps
def token_required():
def _token_required(f):
@wraps(f)
def __token_required(*args, **kwargs):
token = None
if 'token' in request.headers:
token = request.headers['token']
if not token:
return "no token"
return f(*args, **kwargs)
return __token_required
return _token_required
Just add to specific endpoint when token is required:
@token_required()
def get(self, user_id):
...
Hope this helps.
来源:https://stackoverflow.com/questions/58800880/apply-flask-methodview-decorator-just-for-some-methods