如何使用Bottle HTTPError在JSON中返回错误消息? [英] How to return error messages in JSON with Bottle HTTPError?

查看:111
本文介绍了如何使用Bottle HTTPError在JSON中返回错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回以下HTTPError的瓶子服务器:

I have a bottle server that returns HTTPErrors as such:

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

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

When I receive this response in the browser, I'd like to be able to pick out the error message given. As it is right now I can see the error message in the response's responseText field, but it's buried in an HTML string that I'd rather not parse if I don't have to.

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

Is there any way I can specifically set the error message in Bottle so I can pick it out in JSON in the browser?

推荐答案

HTTPError使用预定义的HTML模板来构建响应的正文.除了使用HTTPError之外,您还可以使用response以及相应的状态代码和正文.

HTTPError uses a predefined HTML template to build the body of the response. Instead of using HTTPError you can use response with the appropriate status code and body.

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)

这篇关于如何使用Bottle HTTPError在JSON中返回错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆