Flask重写异常类实现Restful风格的返回结果

  • 环境:Python3.10 Flask3.0.2

在Flask的异常基类werkzeug.exceptions.HTTPException中能看到,该类的get_body()方法将异常信息拼接成了HTML文本:

def get_body(
    self,
    environ: WSGIEnvironment | None = None,
    scope: dict | None = None,
) -> str:
    """Get the HTML body."""
    return (
        "<!doctype html>\n"
        "<html lang=en>\n"
        f"<title>{self.code} {escape(self.name)}</title>\n"
        f"<h1>{escape(self.name)}</h1>\n"
        f"{self.get_description(environ)}\n"
    )

def get_headers(
    self,
    environ: WSGIEnvironment | None = None,
    scope: dict | None = None,
) -> list[tuple[str, str]]:
    """Get a list of headers."""
    return [("Content-Type", "text/html; charset=utf-8")]

返回的body信息如下:

在这里插入图片描述

如果想要Restful,应该返回Json格式的结果,重写异常类代码如下:

from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500  # 默认情况下的错误
    msg = "Sorry, we make a mistake (^.^)"
    error_code = 999  # 自己的错误码

    def __init__(self, msg=None, code=None, error_code=None, headers=None):
        if code:
            self.code = code
        if error_code:
            self.error_code = error_code
        if msg:
            self.msg = msg
        super(APIException, self).__init__(msg, None)

    def get_body(self, environ, scope):
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            # request="POST /v1/client/register"
            request=request.method + " " + self.get_url_no_param()
            # 让客户端知道是哪一个接口产生的异常
        )
        text = json.dumps(body)
        return text

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split("?")
        return main_path[0]

    def get_headers(self, environ, scope):
    	# Content-Type也需要改
        return [("Content-Type", "application/json")]

此时,返回的body是这样的:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值