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

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

当我在浏览器中收到此响应时,我希望能够挑选出给出的错误消息。现在,我可以在响应的responseText字段中看到错误消息,但是该错误消息隐藏在HTML字符串中,如果不需要的话,我宁愿不对其进行解析。

有什么方法可以在Bottle中专门设置错误消息,以便可以在浏览器中以JSON格式选择错误消息?

最佳答案

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)

10-07 14:26
查看更多