小编gpo*_*lek的帖子

使用自定义HTTP代码进行Flask abort()

我在项目中使用Flask框架和纯json api。它仅呈现json响应,而没有html或静态文件。

我正在尝试使用自定义的http代码来实现abort()函数,在我的情况下,默认情况下未定义204(无内容)。我目前有类似的代码:

# Error define
class NoContent(HTTPException):
    code = 204
    description = ('No Content')

abort.mapping[204] = NoContent

def make_json_error(ex):
    response = jsonify(error=str(ex))
    response.status_code = (ex.code
                        if isinstance(ex, HTTPException)
                        else 500)
    return response

custom_exceptions = {}
custom_exceptions[NoContent.code] = NoContent

for code in custom_exceptions.iterkeys():
    app.error_handler_spec[None][code] = make_json_error

# Route
@app.route("/results/<name>")
def results(name=None):
    return jsonify(data=results) if results else abort(204)
Run Code Online (Sandbox Code Playgroud)

它收到如下响应时效果很好:

127.0.0.1 - - [02/Dec/2014 10:51:09] "GET /results/test HTTP/1.1" 204 -
Run Code Online (Sandbox Code Playgroud)

但是没有任何内容。它不会呈现任何内容,甚至不会在浏览器中呈现空白白页。

我可以使用错误处理程序

@app.errorhandler(204)
def error204(e):
    response = jsonify(data=[])
    return response …
Run Code Online (Sandbox Code Playgroud)

python exception flask http-status-code-204

1
推荐指数
1
解决办法
3313
查看次数

标签 统计

exception ×1

flask ×1

http-status-code-204 ×1

python ×1