当flask-jwt扩展令牌过期时,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错误响应?
发布于 2017-11-16 03:18:32
这里记录了这样的示例:http://flask-jwt-extended.readthedocs.io/en/latest/changing_default_behavior.html
API文档在这里:http://flask-jwt-extended.readthedocs.io/en/latest/api.html#module-flask_jwt_extended
发布于 2018-07-07 11:01:19
如果您希望提供能够更改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响应有效负载。
https://stackoverflow.com/questions/47298799
复制相似问题