Skip to main content
 首页 » 编程设计

python之使用自定义 http 代码的 Flask abort()

2025年05月04日14leader

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

我正在尝试使用自定义 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) 

效果很好,我得到的回复如下:

127.0.0.1 - - [02/Dec/2014 10:51:09] "GET /results/test HTTP/1.1" 204 - 

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

我可以使用错误处理器

@app.errorhandler(204) 
def error204(e): 
    response = jsonify(data=[]) 
    return response 

但它返回 200 个 http 代码。这里需要204。当我在 error204() 行中添加时:

response.status_code = 204 

它再次不渲染任何东西。

我被卡住了,我不知道这种方法哪里有错误。请帮忙。

如果我的方法从设计角度来看是错误的,请提出其他建议。

提前致谢。

请您参考如下方法:

记住,HTTP 204 is "No Content" . RFC 7231 (和它之前的 RFC 2616)要求用户代理忽略最后一个标题行之后的所有内容:

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body ... A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.

~ RFC 7231 (强调我的)

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

~ RFC 2616