【发布时间】:2020-06-05 00:57:24
【问题描述】:
为了在 flask webapp 中向客户端返回 400/500 响应,我看到了以下约定:
中止
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()
【问题讨论】: