#!/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