小编典典

在Flask中使用HTTP身份验证时的标准401响应

flask

在flask中,我使用以下代码段启用HTTP身份验证:

def authenticate():
    return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})

现在,根据我过去使用Flask的经验,如果某人的凭据不正确,我想让他们知道我可以打电话给:

abort(401)

这为你提供了基本的apache 401响应。有谁知道我如何使用上面的代码片段实现这一目标?

谢谢


阅读 1645

收藏
2020-04-07

共1个答案

小编典典

在Flask中,自定义错误响应确实非常容易。创建一个仅将参数作为HTTP错误状态代码的函数,使其返回flask.Response实例,并使用@ app.errorhandler对其进行修饰。

@app.errorhandler(401)
def custom_401(error):
    return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})

然后,你可以使用abort(401)自己内心的满足感。

2020-04-07