app_response.py 4.33 KB
Newer Older
qunfeng qiu's avatar
qunfeng qiu committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Version: 1.0
@Python Version:3.6.6
@Author: ludq1
@Email: ludq1@chinaunicom.cn
@date: 2023/04/07 11:40:00
@Description:
"""

from .base_const import ConstResponseCode
from ..globalutility import Utility


class AppResponse:
    r"""
    标准返回数据的封装,包含 code,msg,data等key的标准dict的json表示,不依赖任何其他应用基础类
    """

    code: str = None
    message: str = None
    data = None
    other_data: dict = None
    _status_code: int = None

    def __init__(
            self,
            code: str = None, message: str = None, data=None, other_data: dict = None,
            status_code: int = 200,
    ):
        r"""
        初始化,默认为OK的返回

        :param code: 默认为 SysError
        :param message: 默认为 系统错误
        :param data:
        :param other_data:
        :param status_code:
        """
        self.code: str = code or ConstResponseCode.CODE_OK
        self.message: str = message or ConstResponseCode.gen_msg_for_code(self.code)
        self.other_data = other_data if other_data is not None else dict()
        self.data = data
        self.status_code = status_code

    @classmethod
    def from_dict(
            cls,
            source_dict: dict,
            key_for_msg: str = "message",
            key_for_data: str = "data",
            key_for_code: str = "code",
            key_for_status_code: str = "status_code",
    ):
        r"""
        根据 source_dict(包含 code 和 nessage  key的dict) 生成 AppResponse

        :param source_dict:
        :param key_for_code:
        :param key_for_data:
        :param key_for_msg:
        :param key_for_status_code:
        :return:
        """
        if not source_dict:
            raise RuntimeError("AppResponse解析dict对象出错:dict对象为空")

        result: AppResponse = AppResponse()

        key_for_code = key_for_code or "code"
        tmp_code = source_dict.get(key_for_code)
        if not tmp_code:
            raise RuntimeError(Utility.join_str("AppResponse解析dict对象出错:dict对象的", key_for_code, "不合规"))
        result.code = str(tmp_code)

        key_for_msg = key_for_msg or "message"
        tmp_msg = source_dict.get(key_for_msg) or ""
        result.message = tmp_msg

        key_for_data = key_for_data or "data"
        tmp_data = source_dict.get(key_for_data)
        result.data = tmp_data

        key_for_status_code = key_for_status_code or "status_code"
        tmp_data = source_dict.get(key_for_status_code)
        result.status_code = tmp_data

        for tmp_key, tmp_value in source_dict.items():
            if tmp_key not in {key_for_code, key_for_msg, key_for_data, key_for_status_code}:
                continue
            result.other_data[tmp_key] = tmp_value

        return result

    def __str__(self):
        r"""
        字符串表示, 使用json字符串表示

        Returns:

        """
        return Utility.dict2jsonstr(self.gen_dict())

    def __repr__(self):
        r"""
        字符串表示,使用 __str__ , 不会返回None,至少时 EMPTY字符串

        Returns:

        """
        return self.__str__()

    def gen_dict(self) -> dict:
        r"""
        生成带有 code,message的标准dict

        Returns:

        """
        ret_dict = {"code": self.code, "message": self.message, "status_code": self.status_code}

        if self.other_data:
            for key, value in self.other_data.items():
                ret_dict[key] = value

        if self.data is not None:
            ret_dict['data'] = self.data

        return ret_dict

    @property
    def status_code(self) -> int:
        r"""
        status_code 属性

        :return:
        """
        if self._status_code is None or self._status_code < 1:
            self._status_code = 200
        return self._status_code

    @status_code.setter
    def status_code(self, status_code: int):
        r"""
        status_code 属性

        :param status_code:
        :return:
        """
        self._status_code = status_code

    def is_ok(self) -> bool:
        r"""
        验证code是否等于OK

        """
        return self.code == ConstResponseCode.CODE_OK