如何在Python中使用装饰器执行身份验证?

时间:2020-09-09 10:04:54

标签: python python-3.x flask

我正在实现Flask-RESTFul API,我从邮递员那里收到令牌,并将其与我在代码中配置的令牌进行比较,如下所示:

file: functions.py

def authenticate():
    headers = flask.request.headers
    bearer = headers.get('Authorization')
    token = bearer.split()[1]
    try:
        if str(hashlib.md5(b'Token_String').hexdigest()) == token:
            logger.info('Token authentication successful.')
            return True
        else:
            logger.error('Token autherization failed. Please check the token supplied.')
            return False
    except Exception as e:
        if token is None:
            logger.info('Token cannot be null. Supply a token with API call.')
            return {'message': 'Token cannot be null. Exception: {error}'.format(error=e)}, 400
        else:
            logger.info('Token cannot be null. Supply a token with API call.')
            return {'message': 'Error reading token. Cannot be Null/Empty. Exception: {error}'.format(error=e)}, 400

这是我的API的get方法:

class APIClass(Resource):

    @classmethod
    def get(self):
        logger.info('Initiating get()')
        if fc.authenticate():
            run_some_sql_statements
        else:
            return {'message': 'Token authentication failed'}, 401
        pass

除了使用IF条件之外,还有一种方法可以使用:authenticate中的functions.py作为get()顶部的装饰器。

我尝试这样做,并遇到以下错误:

from validations import functions as fc     

@classmethod
@fc.authenticate
def get(self):

但是我看到编译错误:Function 'authenticate' lacks a positional argument

任何人都可以让我知道我在这里犯的错误以及如何纠正它吗?

1 个答案:

答案 0 :(得分:0)

烧瓶相关文档包含有关资源方法装饰器的部分: https://flask-restful.readthedocs.io/en/latest/extending.html#resource-method-decorators

class APIClass(Resource):
    method_decorators = [authenticate]
相关问题