一些好用的方法

#生成随机数
def gen_random_string(str_len):
    return ''.join(
        random.choice(string.ascii_letters + string.digits) for _ in range(str_len))

#md5
def gen_md5(*str_args):
    return hashlib.md5("".join(str_args).encode('utf-8')).hexdigest()


#删除文本前缀
def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    return text



#查询json里的某个值
def query_json(json_content, query, delimiter='.'):
    
    if json_content == "":
        raise exception.ResponseError("response content is empty!")

    try:
        for key in query.split(delimiter):
            if isinstance(json_content, list):
                json_content = json_content[int(key)]
            elif isinstance(json_content, (dict, CaseInsensitiveDict)):
                json_content = json_content[key]
            else:
                raise exception.ParseResponseError(
                    "response content is in text format! failed to query key {}!".format(key))
    except (KeyError, ValueError, IndexError):
        raise exception.ParseResponseError("failed to query json when extracting response!")

    return json_content


#将dict的key小写
def lower_dict_keys(origin_dict):
    """ convert keys in dict to lower case
    e.g.
        Name => name, Request => request
        URL => url, METHOD => method, Headers => headers, Data => data
    """
    if not origin_dict or not isinstance(origin_dict, dict):
        return origin_dict

    return {
        key.lower(): value
        for key, value in origin_dict.items()
    }

def lower_config_dict_key(config_dict):
    """ convert key in config dict to lower case, convertion will occur in two places:
        1, all keys in config dict;
        2, all keys in config["request"]
    """
    config_dict = lower_dict_keys(config_dict)
    if "request" in config_dict:
        config_dict["request"] = lower_dict_keys(config_dict["request"])

    return config_dict

你可能感兴趣的:(一些好用的方法)