【问题标题】:Python flask and custom client error messagesPython烧瓶和自定义客户端错误消息
【发布时间】:2013-08-06 13:36:08
【问题描述】:

我目前正在为我正在开发的应用程序编写 REST API。该应用程序是使用烧瓶在 python 中编写的。我有以下内容:

try:
    _profile = profile(
        name=request.json['name'],
        password=profile.get_salted_password('blablabla'),
        email=request.json['email'],
        created_by=1,
        last_updated_by=1
    )
except AssertionError:
    abort(400)

session = DatabaseEngine.getSession()
session.add(_profile)
try:
    session.commit()
except IntegrityError:
    abort(400)

错误处理程序如下所示:

@app.errorhandler(400)
def not_found(error):
    return make_response(standard_response(None, 400, 'Bad request'), 400)

我使用错误 400 来表示 sqlalchemy 模型验证器的问题写入数据库时​​的唯一约束,在这两种情况下,以下错误都会发送到客户端:

{
  "data": null,
  "error": {
    "msg": "Bad request",
    "no": 400
  },
  "success": false
}

有没有办法在仍然使用 abort(400) 的同时以某种方式设置错误,以便错误处理程序可以在结果中为错误对象添加额外信息?

我希望它更符合:

{
  "data": null,
  "error": {
    "msg": "(IntegrityError) duplicate key value violates unique constraint profile_email_key",
    "no": 400
  },
  "success": false
}

【问题讨论】:

    标签: python error-handling flask


    【解决方案1】:

    您可以直接将自定义响应放入 abort() 函数中:

    abort(make_response("Integrity Error", 400))
    

    或者,你可以把它放在错误处理函数中

    @app.errorhandler(400)
    def not_found(error):
    resp = make_response("Integrity Error", 400)
    return resp
    

    【讨论】:

    • 它可以产生输出,但如果我这样做,似乎没有调用错误 400 处理程序。由于我计划在错误处理程序中进行一些日志记录,有没有办法仍然结束?
    • 是的,从那以后就不行了,我又回到了我开始的地方,所有 400 都将是 Integrity Error 而不是 Bad Request。我需要让自定义错误文本 都出现在错误处理程序中。 :)
    • abort 在当前 api 中没有响应。 flask.pocoo.org/docs/api
    【解决方案2】:

    errorhandler 也可以采用异常类型:

    @app.errorhandler(AssertionError)
    def handle_sqlalchemy_assertion_error(err):
        return make_response(standard_response(None, 400, err.message), 400)
    

    【讨论】:

    • 是的,这就是我要找的那个。有没有办法捕获未绑定到处理程序的错误,例如“catch-all”,以便我也可以格式化并将其处理给客户端?
    • make_response 和 standard_response 对我不起作用。但这确实:“def handle_sqlalchemy_error(err): return err.message, 400”
    【解决方案3】:

    我知道游戏迟到了,但对于任何想要另一种解决方案的人,我的答案是基于 @codegeek 的答案。

    我能够在我的ServerResponse.py 模块中完成与以下类似的事情:

    def duplicate(message=""):
        response = make_response()
        response.status_code = 409
        response.headers = {
            "X-Status-Reason" : message or "Duplicate entry"
        }
        abort(response)
    

    那我可以打电话了

    ServerResponse.duplicate('Duplicate submission. An article with a similar title already exists.')
    

    这使我的 AngularJS 应用程序可以轻松检查响应状态并显示 X-Status-Reason 默认或自定义消息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多