flask-jwt-extended:自定义错误消息

时间:2017-11-15 03:20:46

标签: python flask jwt flask-jwt-extended

当flask-jwt-extended标记已过期时,HTTP请求将导致此JSON响应

{
  "msg": "Token has expired"
}

我的应用程序有一个固定的错误响应格式:

{
    "message": "Project name 'Test 8' already exist.",
    "error": {
        "resource": "Project",
        "field": "project_name",
        "code": "already_exists",
        "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique constraint \"project_name_idx\"\nDETAIL:  Key (project_name)=(Test 8) already exists.\n [SQL: 'INSERT INTO project (project_name, project_root, deadline_id) VALUES (%(project_name)s, %(project_root)s, %(deadline_id)s) RETURNING project.project_id'] [parameters: {'project_name': 'Test 8', 'project_root': 'P:\\\\Test8', 'deadline_id': 2}]"
    }
}

如何自定义flask-jwt-extended错误响应?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

如果要提供能够更改Flask JWT返回的标准JSON错误响应的功能,以便可以发送回自己的标准错误消息格式,则必须使用JWTManager加载器函数。具体来说就是expired_token_loader

# Using the expired_token_loader decorator, we will now call
# this function whenever an expired but otherwise valid access
# token attempts to access an endpoint
@jwt.expired_token_loader
def my_expired_token_callback():
    return jsonify({
        'status': 401,
        'sub_status': 42,
        'msg': 'The token has expired'
    }), 401

执行此操作可能最终变得很乏味,尽管在验证令牌时必须以所有不同方式使用所有加载程序功能。

您可以考虑编写自己的通用实用程序函数,该函数返回任何响应对象文本属性的值部分,然后将其放入需要返回的固定错误消息格式中。

示例:

def extract_response_text(the_response):
    return the_response.json().get('msg')

我也忘了提及您可以使用上面的示例并使用@ app.after_request装饰器。这将允许您在返回响应之前将所有应用程序端点配置为使用此方法。您可以在其中更改或创建特定的JSON响应有效载荷。