代码改变世界

使用bottle进行web开发(4):HTTPError

2017-06-19 12:18  很大很老实  阅读(597)  评论(0编辑  收藏  举报
from bottle import error
@error(404)
def error404(error):
    return 'Nothing here, sorry'

上述代码,是对404的定义,这里注意,有一个HTTPError,

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)