如何为flask注册定制的http状态码?

2024-09-27 22:35:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我自己的http状态码添加到我的Flask应用程序中。这是我的密码:

from werkzeug import exceptions

class UnrecognizedParametersOrCombination(exceptions.HTTPException):
    code = 460
    description = 'The query parameters or their combination are not recognized!'


exceptions.default_exceptions[460] = UnrecognizedParametersOrCombination

但是当我调用abort(460)时,我得到了一个错误: LookupError: no exception for 460

似乎我没有正确地将新异常注册到werkzeug default exceptions。官方文件在这一部分很模糊。我该怎么做?你知道吗


Tags: fromimport应用程序httpdefault密码flask状态
3条回答

好吧,我想出来了。根据文件: http://flask.pocoo.org/docs/1.0/errorhandling/ 这是行不通的。我们能做的是定义一个异常,raise()它而不是abort()它。现在看来,werkzeug不再支持在其默认异常中注册自定义的http状态码。。。你知道吗

所以现在我的工作代码是:

from werkzeug import exceptions

class UnrecognizedParametersOrCombination(exceptions.HTTPException):
    code = 460
    description = 'The query parameters or their combination are not recognized!'


def handle_460(e):
    return render_template('460.html')


app.register_error_handler(UnrecognizedParametersOrCombination, handle_460)

现在我需要用raise UnrecognizedParametersOrCombination()而不是abort(460)来响应。所以,答案是200而不是没有官方支持的460。你知道吗

尝试中止映射?你知道吗

abort.mappings[460] = UnrecognizedParametersOrCombination

您不应该这样做,因为这样会破坏与HTTP状态码关联的rfc。HTTP状态码应该是通用的,不会被滥用。我建议您响应一些JSON,比如“status”:“460”,如果您想使用自己的调试代码,就不要将它们用作HTTP响应。你知道吗

相关问题 更多 >

    热门问题