【问题标题】:Flask abort() with custom http code带有自定义 http 代码的烧瓶 abort()
【发布时间】:2015-01-30 14:23:10
【问题描述】:

我在我的项目中使用 Flask 框架和纯 json api。它只呈现没有 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

它再次没有渲染任何东西。

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

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

提前致谢。

【问题讨论】:

  • 您是否尝试过在调试模式下运行应用程序并检查是否引发任何异常。我会在黑暗中刺伤并说某处某处引发了异常。

标签: python exception flask http-status-code-204


【解决方案1】:

您需要在错误处理程序中返回状态码。

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

省略状态码被 Flask 解释为 200。

【讨论】:

    【解决方案2】:

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

    204(无内容)状态码表示服务器已成功完成请求,并且响应负载正文中没有要发送的其他内容... 204响应以第一个空行终止在标头字段之后,因为它不能包含消息正文。

    ~RFC 7231(强调我的)

    204 响应不得包含消息正文,因此始终以标头字段后的第一个空行终止。

    ~RFC 2616

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2011-05-03
      • 2012-08-30
      • 2021-01-13
      • 2019-07-19
      • 2018-04-14
      • 2012-10-30
      相关资源
      最近更新 更多