我正在尝试实现一个装饰器,该装饰器在授予对函数的访问权限之前对用户的令牌进行身份验证。我当前的实现有点不稳定,因为我无法在装饰器中获取本地人,因此我需要执行两个查询。有一个更好的方法吗?
def require_auth(func):
print 'require_auth'
@wraps(func)
def inner():
if 'token' in request.json:
token = request.json['token']
session = Session()
for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==token):
auth_user = instance.username
try:
auth_user
print 'authenticated!'
except NameError:
abort(401)
else:
abort(401)
return func()
return inner
@app.route('/st/projects', methods=['POST'])
@require_auth
def post_project():
session = Session()
for instance in session.query(SQLTypes.User).filter(SQLTypes.User.token==request.json['token']):
auth_user = instance.username
# do something with auth_user
session.close()