my_utils.py 9.07 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
#!/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:
"""

import json
import os
from typing import Union, Optional


class MyUtils:
    """
    基础全局工具类,为了防止依赖循环,此模块不依赖于任何模块
    """

    EMPTY = ''

    @classmethod
    def do_filter_xss(cls, to_filter_str: str) -> str:
        r"""
        防xss处理,将 < 替换成#《#,将 > 替换成 #》#

        Args:
            to_filter_str: string

        Returns:

        """
        if cls.is_empty(to_filter_str):
            return to_filter_str

        to_filter_str = cls.to_str(to_filter_str)
        to_filter_str = to_filter_str.replace('<', '#《#').replace('>', '#》#')
        return to_filter_str

    @classmethod
    def has_attr(cls, a_obj, attr_name: str, must_be_method: bool = False) -> bool:
        r"""
        判断对象是否包含指定的属性,以及该属性是否必须是方法

        Args:
            a_obj:
            attr_name:
            must_be_method:

        Returns:

        """
        if not hasattr(a_obj, attr_name):
            return False

        if not must_be_method:
            return True

        attr_obj = getattr(a_obj, attr_name, None)
        return hasattr(attr_obj, '__call__')

    @classmethod
    def format_dict_to_str_dict(cls, to_format_dict: dict, ignore_none: bool = True,
                                ignore_empty: bool = False) -> dict:
        r"""
        将 to_format_dict 中的 key 和 value 都转换成 str ,

        尤其是 value 如果是 list,tuple,dict,将被转换成 json 格式的字符串,

        如果 value 为 None,则默认移除key , 不移除时将其转换为 null 字符串

        如果 value 为 EMPTY , 则默认不移除

        Args:
            to_format_dict:
            ignore_none:
            ignore_empty:

        Returns:

        """
        if not (to_format_dict is None or isinstance(to_format_dict, dict)):
            raise ValueError('to_format_dict 不是字典')

        ret_dict = {}
        if not to_format_dict:
            return ret_dict

        for tmp_k, tmp_v in to_format_dict.items():
            if tmp_v is None:
                if not ignore_none:
                    tmp_v = 'null'
                    ret_dict[tmp_k] = tmp_v
                continue

            if isinstance(tmp_v, (dict, list, tuple)):
                tmp_v = json.dumps(tmp_v, ensure_ascii=False)
            else:
                tmp_v = str(tmp_v)

            if tmp_v == '':
                if not ignore_empty:
                    ret_dict[tmp_k] = tmp_v
                continue

            ret_dict[tmp_k] = tmp_v

        return ret_dict

    @classmethod
    def dict2jsonstr(cls, a_dict: dict, value_when_obj_is_none: str = 'null') -> str:
        r"""
        将dict转成jsonstr

        Args:
            a_dict: 待转成json字符串的 dict
            value_when_obj_is_none: 当 a_dict 为 None 时返回的字符串,默认为null

        Returns:

        """
        if a_dict is None:
            return value_when_obj_is_none
        elif isinstance(a_dict, dict):
            return json.dumps(a_dict, ensure_ascii=False, default=lambda o: o.__dict__)
        else:
            raise ValueError('参数类型不是字典')

    @classmethod
    def list2jsonstr(cls, a_list: Union[list, tuple], value_when_obj_is_none: str = 'null') -> str:
        r"""
        将list or tuple 转成jsonstr

        Args:
            a_list: 待转成json字符串的 list or tuple
            value_when_obj_is_none: 当 a_list 为 None 时返回的字符串,默认为null

        Returns:

        """
        if a_list is None:
            return value_when_obj_is_none
        elif isinstance(a_list, (list, tuple)):
            return json.dumps(a_list, ensure_ascii=False, default=lambda o: o.__dict__)
        else:
            raise ValueError('参数类型不是list或元组')

    @classmethod
    def jsonstr2json(cls, a_jsonstr: str, b_raise_error_when_illegal: bool = False) -> json:
        r"""
        将 jsonstr 转成 dict

        Args:
            a_jsonstr: json格式的字符串
            b_raise_error_when_illegal: 当字符串不合法时抛出异常还是返回None
        Returns:

        """
        try:
            json_ret = json.loads(a_jsonstr)
            if isinstance(json_ret, dict) or isinstance(json_ret, list):
                return json_ret
            else:
                raise ValueError('json_str不是有效的json字符串')
        except Exception as exception:
            encountered_e = exception

        if encountered_e:
            if b_raise_error_when_illegal:
                raise encountered_e
            else:
                return None

    @classmethod
    def jsonstr2dict(cls, a_jsonstr: str, b_raise_error_when_illegal: bool = False) -> Optional[dict]:
        r"""
        将 jsonstr 转成 dict

        Args:
            a_jsonstr: json格式的字符串
            b_raise_error_when_illegal: 当字符串不合法时抛出异常还是返回None
        Returns:

        """
        try:
            if isinstance(a_jsonstr, dict):
                return a_jsonstr

            a_dict = json.loads(a_jsonstr)
            if isinstance(a_dict, dict):
                return a_dict
            else:
                raise ValueError('json_str不是有效的json字符串')
        except Exception as exception:
            encountered_e = exception

        if encountered_e:
            if b_raise_error_when_illegal:
                raise encountered_e
            else:
                return None

    @classmethod
    def jsonstr2list(cls, a_jsonarrstr: str, b_raise_error_when_illegal: bool = False) -> Optional[list]:
        r"""
        将 jsonstr 转成 list

        Args:
            a_jsonarrstr: jsonarr格式的字符串
            b_raise_error_when_illegal: 当字符串不合法时抛出异常还是返回None
        Returns:

        """
        try:
            if isinstance(a_jsonarrstr, list):
                return a_jsonarrstr

            if isinstance(a_jsonarrstr, tuple):
                return list(a_jsonarrstr)

            a_list = json.loads(a_jsonarrstr)
            if isinstance(a_list, list):
                return a_list
            else:
                raise ValueError('json_str不是有效的jsonarray字符串')
        except Exception as exception:
            encountered_e = exception

        if encountered_e:
            if b_raise_error_when_illegal:
                raise encountered_e
            else:
                return None

    @classmethod
    def get_env(cls, env_name: str) -> str:
        r"""
        获取系统环境变量的内容

        Args:
            env_name:
        Returns:

        """

        env_dict = os.environ

        if env_dict and str(env_name) in env_dict:
            return env_dict[env_name]
        else:
            return ''

    @classmethod
    def to_str(cls, a_obj, trim: bool = False) -> str:
        r"""
        将对象转换为字符串, 当对象为None或对其调用str()函数返回为None时,返回 EMPTY

        Args:
            a_obj:
            trim:

        Returns:

        """
        if a_obj is None:
            return cls.EMPTY
        else:
            if not isinstance(a_obj, str):
                a_obj = str(a_obj)

            if a_obj is None:
                return cls.EMPTY

        if trim:
            a_obj = a_obj.strip()

        return a_obj

    @classmethod
    def is_empty(cls, a_str: str, trim: bool = False) -> bool:
        r"""
        检查字符串是否是空字符串, None和''都是true,其他为false

        Args:
            a_str:
            trim:

        Returns:

        """

        if a_str is None:
            return True
        else:
            if not isinstance(a_str, str):
                a_str = str(a_str)

            if a_str is None:
                return True

        if trim:
            a_str = a_str.strip()

        return a_str == ''

    @classmethod
    def equals(cls, str1: str, str2: str, none_eqaul_empty: bool = False) -> bool:
        r"""
        检查两个字符串是否相同,

        None 和 None 相同

        None 和 空字符串 不相同

        Args:
            str1:
            str2:
            none_eqaul_empty:

        Returns:

        """

        if str1 is None and str2 is None:
            return True

        if str1 is None and none_eqaul_empty:
            str1 = cls.EMPTY

        if str2 is None and none_eqaul_empty:
            str2 = cls.EMPTY

        if (str1 is None and str2 is not None) or (str2 is None and str1 is not None):
            return False

        str1 = cls.to_str(str1)
        str2 = cls.to_str(str2)

        return str1 == str2