像SpringBoot一样使用Flask - 5.统一处理(日志、异常、响应报文)

 接上文《像SpringBoot一样使用Flask - 4.拦截器》,通过拦截器处理一些日志,异常、还有统一的响应报文。

    统一的目的就是为了让前后端调用请求不会因为各自习惯而随意编写,增加技术人员快速上手及代码的可阅读性。

    一、定义一个返回类。是不是很像定义java类、构造函数、方法定义


import json
class JsonResponse(object):
    """
    统一的json返回格式
    """

    def __init__(self, data, code, msg):
        self.data = data
        self.code = code
        self.msg = msg

    @classmethod
    def success(cls, data=None, code=0, msg='success'):
        return cls(data, code, msg)

    @classmethod
    def error(cls, data=None, code=-1, msg='error'):
        return cls(data, code, msg)

    def to_dict(self):
        return {
            "code": self.code,
            "msg": self.msg,
            "data": self.data
        }

    def to_json(self):
        return json.dumps(self , default= lambda obj: obj.__dict__ ,sort_keys=True ,indent=4)

二、在原先TestController中写个测试。可以通过jsonify这个函数,只是需要自己重复写一个json字符串,当作一个对比吧

@test_bp.route('/hello')
def hello_world():  # put application's code here
    return jsonify({"code": 0, "data": "Hello World 2024", "msg": "查询成功"})


@test_bp.route('/json')
def hello_world_two():  # put application's code here
    return JsonResponse.success(data="Hello World 2024", code=200, msg="success").to_json()

    三、运行测试

四、在上面拦截器中,可以增加一些自己的统一异常处理


@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获
    """
    print(str(e))
    app.logger.info(str(e))
    retResponse = JsonResponse.error(code=500, msg=str(e))
    return JsonResponse.to_json(retResponse)


# 请求进入拦截 对应 after_request 正常返回否则异常就被 errorhandler拦截处理
@app.before_request
def pre_request():
    app.logger.debug(f'path:{request.path}')
    app.logger.debug(f'args:{dict(request.args)}')
    app.logger.debug(f'headers:{request.headers}')
    app.logger.debug(f'cookies:{dict(request.cookies)}')
    #app.logger.debug(f'json:{request.json}')

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值