Apply Flask MethodView decorator just for some methods

南笙酒味 提交于 2021-01-28 07:12:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!