flask返回自定义的Response

2023-01-31 00:01:32 flask 返回 自定义
from JSON import dumps
from flask import Response
from flask_api import status
from protocol.errors_pb2 import *


class ErrorResponse(Response):
    def __init__(self, err_code, err_msg=''):
        result = dumps(dict(code=err_code, msg=err_msg))
        Response.__init__(self, result, mimetype='application/json')


class JSONResponse(Response):
    def __init__(self, data, msg=''):
        result = dumps(dict(data=data, code=Error_None, msg=msg))
        Response.__init__(self, result, mimetype='application/json')


class UnauthorizedResponse(Response):
    def __init__(self):
        data = dumps(dict(msg="need login", code=Error_NeedLogin, data=None))
        Response.__init__(self, data, mimetype='application/json', status=status.Http_401_UNAUTHORIZED)

注意:一定要使用json.dumps来转换最后的结果

相关文章