为了将400/500
响应返回到flask
Webapp中的客户端,我已经看到以下约定:
import flask
def index(arg):
return flask.abort("Invalid request", 400)
def index(arg):
return ("Invalid request", 400)
import flask
def index(arg):
return flask.Response("Invalid request", 400)
有什么区别,何时会首选?
来自Java/Spring
,我习惯于使用一个与之关联的状态代码来定义一个自定义异常,然后在应用程序抛出该异常时,带有该状态代码的响应会自动返回给用户(而不是必须显式捕获它并返回一个如上所示)。这可能flask
吗?这是我的小尝试
from flask import Response
class FooException(Exception):
""" Binds optional status code and encapsulates returing Response when error is caught """
def __init__(self, *args, **kwargs):
code = kwargs.pop('code', 400)
Exception.__init__(self)
self.code = code
def as_http_error(self):
return Response(str(self), self.code)
然后使用
try:
something()
catch FooException as ex:
return ex.as_http_error()
最佳实践是创建您的自定义异常类,然后通过错误处理程序装饰器向Flask应用注册。您可以从业务逻辑中引发自定义异常,然后允许Flask Error Handler处理任何自定义的异常。(类似的方法也可以在春季完成。)
您可以使用如下所示的装饰器并注册自定义异常。
@app.errorhandler(FooException)
def handle_foo_exception(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
您可以在此处了解更多有关实现API异常的信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句