【问题标题】:flask-jwt-extended: customizing error messageflask-jwt-extended:自定义错误消息
【发布时间】:2018-04-28 04:04:43
【问题描述】:

当 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错误响应?

【问题讨论】:

    标签: python flask jwt flask-jwt-extended


    【解决方案1】:
    【解决方案2】:

    如果您希望能够更改由 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 响应负载。

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2020-02-04
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2014-03-05
      相关资源
      最近更新 更多