【发布时间】: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