【问题标题】:How to return error messages in JSON with Bottle HTTPError?如何使用 Bottle HTTPError 以 JSON 格式返回错误消息?
【发布时间】:2015-08-31 12:15:06
【问题描述】:

我有一个像这样返回 HTTPErrors 的瓶子服务器:

return HTTPError(400, "Object already exists with that name")

当我在浏览器中收到此响应时,我希望能够挑选出给出的错误消息。就像现在一样,我可以在响应的 responseText 字段中看到错误消息,但它隐藏在一个 HTML 字符串中,如果我不需要,我宁愿不解析。

有什么方法可以专门设置 Bottle 中的错误消息,以便我可以在浏览器中以 JSON 格式将其挑选出来?

【问题讨论】:

  • 不相关,但是...这是实际错误吗?如果是这样,它不应该是400 状态码。 409 Conflict 应该返回恕我直言,

标签: python json bottle


【解决方案1】:

HTTPError 使用预定义的 HTML 模板来构建响应的正文。除了使用HTTPError,您还可以使用response 和适当的状态代码和正文。

import json
from bottle import run, route, response

@route('/text')
def get_text():
    response.status = 400
    return 'Object already exists with that name'

@route('/json')
def get_json():
    response.status = 400
    response.content_type = 'application/json'
    return json.dumps({'error': 'Object already exists with that name'})

# Start bottle server.
run(host='0.0.0.0', port=8070, debug=True)

【讨论】:

    【解决方案2】:

    我一直在寻找一种类似的方法,将所有错误消息作为 JSON 响应来处理。上述解决方案的问题是,他们没有以一种很好和通用的方式来处理它,即处理任何可能的弹出错误,而不仅仅是定义的 400 等。恕我直言,最干净的解决方案是覆盖默认错误,并且然后使用自定义瓶子对象:

    class JSONErrorBottle(bottle.Bottle):
        def default_error_handler(self, res):
            bottle.response.content_type = 'application/json'
            return json.dumps(dict(error=res.body, status_code=res.status_code))
    

    传递的res 参数具有更多关于抛出错误的属性,可能会返回,请参阅默认模板的代码。尤其是 .status.exception.traceback 似乎相关。

    【讨论】:

    • 如果您描述了如何使用这样的类,那将会很有用。简单地声明这个类似乎并没有做任何事情——你如何告诉 Bottle 使用它作为它的默认错误处理程序?
    【解决方案3】:

    刚刚开始使用瓶子,但会推荐更多类似的东西:

    import json
    from bottle import route, response, error, abort
    
    @route('/text')
    def get_text():
        abort(400, 'object already exists with that name')
    
    # note you can add in whatever other error numbers
    # you want, haven't found a catch-all yet
    # may also be @application.error(400)
    @error(400) #might be @application.error in some usages i think.
    def json_error(error):
        """for some reason bottle don't deal with 
        dicts returned the same way it does in view methods.
        """
        error_data = {
            'error_message': error.body
        }
        response.content_type = 'application/json'
        return json.dumps(error_data)
    

    没有运行上面的,所以期待错误,但你明白了要点。

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2012-10-21
      • 2020-01-23
      • 2016-10-06
      • 1970-01-01
      • 2012-08-30
      相关资源
      最近更新 更多