【问题标题】:How to use a decorator in Python to perform authentication?如何在 Python 中使用装饰器来执行身份验证?
【发布时间】:2020-09-09 10:04:54
【问题描述】:

我正在实现一个 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 from functions.py file 作为我的 get() 之上的装饰器。

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

from validations import functions as fc     

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

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

谁能告诉我我在这里犯了什么错误,我该如何纠正?

【问题讨论】:

    标签: python python-3.x flask


    【解决方案1】:

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

    class APIClass(Resource):
        method_decorators = [authenticate]
    

    【讨论】:

    • 在文档中:method_decorators = {'get': [cache]}
    猜你喜欢
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2013-10-31
    • 2020-05-06
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多