我想知道是否可以对类中的某些方法使用装饰器,例如,在下面的代码中,我希望token_required
装饰除POST以外的所有方法,我怎么可能实现吗?
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"
答案 0 :(得分:1)
有几种方法。
1)将request method
上的条件添加到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)С为任意点创建一个通用decorator
并使用不具有decorators
属性的他。
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
仅在需要令牌时添加到特定端点:
@token_required()
def get(self, user_id):
...
希望这会有所帮助。