fish_common 基本函数包¶
fish_common.conf_as_dict(conf_filename[, …]) |
读入 ini 配置文件,返回根据配置文件内容生成的字典类型变量; |
fish_common.SingleTon |
申明一个单例类,可以作为需要单例类时候申明用的父类 |
fish_common.get_uuid(kind) |
获得不重复的 uuid,可以是包含时间戳的 uuid,也可以是完全随机的;基于 Python 的 uuid 类进行封装和扩展; |
fish_common.has_space_element(source) |
判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组 |
fish_common.if_json_contain(left_json, …) |
判断一个 json 是否包含另外一个 json 的 key,并且 value 相等; |
fish_common.sorted_list_from_dict(p_dict[, …]) |
根据字典的 value 进行排序,并以列表形式返回 |
fish_common.join_url_params(dic) |
根据传入的键值对,拼接 url 后面 ? 的参数,比如 ?key1=value1&key2=value2 |
fish_common.has_special_char(p_str[, …]) |
检查字符串是否含有指定类型字符 |
fish_common.find_files(path[, exts]) |
查找路径下的文件,返回指定类型的文件列表 |
fish_common.get_distinct_elements(items[, key]) |
去除序列中的重复元素,使得剩下的元素仍然保持顺序不变,对于不可哈希的对象,需要指定 key ,说明去重元素 |
fish_common.sort_objs_by_attr(objs, key[, …]) |
对原生不支持比较操作的对象根据属性排序 |
fish_common.get_query_param_from_url(url) |
从 url 中获取 query 参数字典 |
fish_common.get_sub_dict(data_dict, key_list) |
从字典中提取子集 |
fish_common.paging(data_list[, …]) |
获取分组列表数据 |
fish_common.camelcase_to_underline(param_dict) |
将驼峰命名的参数字典键转换为下划线参数 |
fish_common.find_same_between_dicts(dict1, dict2) |
查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象 |
fish_common.yaml_conf_as_dict(file_path[, …]) |
读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量 |
fish_common.serialize_instance(obj) |
对象序列化 |
fish_common 包含的是最常用用的一些函数和类。
-
class
fish_common.SingleTon¶ 申明一个单例类,可以作为需要单例类时候申明用的父类
Param: 无 返回: 无 举例如下:
print('--- class singleton demo ---') t1 = SingleTon() t1.x = 2 print('t1.x:', t1.x) t2 = SingleTon() t1.x += 1 print('t1.x:', t1.x) print('t2.x:', t2.x) print('---')
执行结果:
--- class singleton demo --- t1.x: 2 t1.x: 3 t2.x: 3 ---
-
fish_common.camelcase_to_underline(param_dict)¶ 将驼峰命名的参数字典键转换为下划线参数
Param: - param_dict: (dict) 请求参数字典
返回: - temp_dict: (dict) 转换后的参数字典
举例如下:
print('--- transform_hump_to_underline demo---') hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right_name': 'name'} underline_param_dict = transform_hump_to_underline(hump_param_dict ) print(underline_param_dict ) print('---')
执行结果:
--- transform_hump_to_underline demo--- {'first_name': 'Python', 'second_name': 'san', 'right_name': 'name'} ---
-
fish_common.conf_as_dict(conf_filename, encoding=None)¶ 读入 ini 配置文件,返回根据配置文件内容生成的字典类型变量;
Param: - conf_filename: (string) 需要读入的 ini 配置文件长文件名
- encoding: (string) 文件编码
返回: - flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
- d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致
- count: (int) 读取到的配置文件有多少个 key 的数量
举例如下:
print('--- conf_as_dict demo---') # 定义配置文件名 conf_filename = 'test_conf.ini' # 读取配置文件 ds = conf_as_dict(conf_filename) # 显示是否成功,所有 dict 的内容,dict 的 key 数量 print('flag:', ds[0]) print('dict:', ds[1]) print('length:', ds[2]) d = ds[1] # 显示一个 section 下的所有内容 print('section show_opt:', d['show_opt']) # 显示一个 section 下面的 key 的 value 内容 print('section show_opt, key short_opt:', d['show_opt']['short_opt']) # 读取一个复杂的section,先读出 key 中的 count 内容,再遍历每个 key 的 value i = int(d['get_extra_rules']['erule_count']) print('section get_extra_rules, key erule_count:', i) for j in range(i): print('section get_extra_rules, key erule_type:', d['get_extra_rules']['erule_'+str(j)]) print('---')
执行结果:
--- conf_as_dict demo--- flag: True dict: (omit) length: 7 section show_opt: {'short_opt': 'b:d:v:p:f:', 'long_opt': 'region=,prov=,mer_id=,mer_short_name=,web_status='} section show_opt, key short_opt: b:d:v:p:f: section get_extra_rules, key erule_count: 2 section get_extra_rules, key erule_type: extra_rule_1 section get_extra_rules, key erule_type: extra_rule_2 ---
-
fish_common.find_files(path, exts=None)¶ 查找路径下的文件,返回指定类型的文件列表
Param: - path: (string) 查找路径
- exts: (list) 文件类型列表,默认为空
返回: - files_list: (list) 文件列表
举例如下:
print('--- find_files demo ---') path1 = '/root/fishbase_issue' all_files = find_files(path1) print(all_files) exts_files = find_files(path1, exts=['.png', '.py']) print(exts_files) print('---')
执行结果:
--- find_files demo --- ['/root/fishbase_issue/test.png', '/root/fishbase_issue/head.jpg','/root/fishbase_issue/py/man.png' ['/root/fishbase_issue/test.png', '/root/fishbase_issue/py/man.png'] ---
-
fish_common.find_same_between_dicts(dict1, dict2)¶ 查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象
Param: - dict1: (dict) 比较的字典 1
- dict2: (dict) 比较的字典 2
返回: - dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组
举例如下:
print('--- find_same_between_dicts demo---') dict1 = {'x':1, 'y':2, 'z':3} dict2 = {'w':10, 'x':1, 'y':2} res = find_same_between_dicts(dict1, dict2) print(res.item) print(res.key) print(res.value) print('---')
执行结果:
--- find_same_between_dicts demo--- set([('x', 1)]) {'x', 'y'} {1} ---
-
fish_common.get_distinct_elements(items, key=None)¶ 去除序列中的重复元素,使得剩下的元素仍然保持顺序不变,对于不可哈希的对象,需要指定 key ,说明去重元素
Param: - items: (list) 需要去重的列表
- key: (hook函数) 指定一个函数,用来将序列中的元素转换成可哈希类型
返回: - result: (generator) 去重后的结果的生成器
举例如下:
print('--- remove_duplicate_elements demo---') list_demo = remove_duplicate_elements([1, 5, 2, 1, 9, 1, 5, 10]) print(list(list_demo)) list2 = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}] dict_demo1 = remove_duplicate_elements(list2, key=lambda d: (d['x'], d['y'])) print(list(dict_demo1)) dict_demo2 = remove_duplicate_elements(list2, key=lambda d: d['x']) print(list(dict_demo2)) dict_demo3 = remove_duplicate_elements(list2, key=lambda d: d['y']) print(list(dict_demo3)) print('---')
执行结果:
--- remove_duplicate_elements demo--- [1, 5, 2, 9, 10] [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}] [{'x': 1, 'y': 2}, {'x': 2, 'y': 4}] [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}] ---
-
fish_common.get_query_param_from_url(url)¶ 从 url 中获取 query 参数字典
Param: - url: (string) 需要获取参数字典的 url
返回: - query_dict: (dict) query 参数的有序字典,字典的值为 query 值组成的列表
举例如下:
print('--- get_query_param_from_url demo---') url = 'http://localhost:8811/mytest?page_number=1&page_size=10' query_dict = get_query_param_from_url(url) print(query_dict['page_size']) print('---')
执行结果:
--- get_query_param_from_url demo--- ['10'] ---
-
fish_common.get_random_str(length, letters=True, digits=False, punctuation=False)¶ 获得指定长度,不同规则的随机字符串,可以包含数字,字母和标点符号
Param: - length: (int) 随机字符串的长度
- letters: (bool) 随机字符串是否包含字母,默认包含
- digits: (bool) 随机字符串是否包含数字,默认不包含
- punctuation: (bool) 随机字符串是否包含特殊标点符号,默认不包含
返回: - random_str: (string) 指定规则的随机字符串
举例如下:
print('--- get_random_str demo---') print(get_random_str(6)) print(get_random_str(6, digits=True)) print(get_random_str(12, punctuation=True)) print(get_random_str(6, letters=False, digits=True)) print(get_random_str(12, letters=False, digits=True, punctuation=True)) print('---')
执行结果:
--- get_random_str demo--- nRBDHf jXG5wR )I;rz{ob&Clg 427681 *"4$0^`2}%9{ ---
-
fish_common.get_sub_dict(data_dict, key_list, default_value='default_value')¶ 从字典中提取子集
Param: - data_dict: (dict) 需要提取子集的字典
- key_list: (list) 需要获取子集的键列表
- default_value: (string) 当键不存在时的默认值,默认为 default_value
返回: - sub_dict: (dict) 子集字典
举例如下:
print('--- get_sub_dict demo---') dict1 = {'a': 1, 'b': 2, 'list1': [1,2,3]} list1 = ['a', 'list1', 'no_key'] print(get_sub_dict(dict1, list1)) print(get_sub_dict(dict1, list1, default_value='new default')) print('---')
执行结果:
--- get_sub_dict demo--- {'a': 1, 'list1': [1, 2, 3], 'no_key': 'default_value'} {'a': 1, 'list1': [1, 2, 3], 'no_key': 'new default'} ---
-
fish_common.get_time_uuid()¶ 获得不重复的 uuid,可以是包含时间戳的 uuid,也可以是完全随机的;基于 Python 的 uuid 类进行封装和扩展;
支持 get_time_uuid() 这样的写法,不需要参数,也可以表示生成包含时间戳的 uuid,兼容 v1.0.12 以及之前版本;
Param: - kind: (int) uuid 类型,整形常量 udTime 表示基于时间戳, udRandom 表示完全随机
返回: - result: (string) 返回类似 66b438e3-200d-4fe3-8c9e-2bc431bb3000 的 uuid
举例如下:
print('--- uuid demo ---') # 获得带时间戳的uuid for i in range(2): print(get_uuid(udTime)) print('---') # 时间戳 uuid 的简单写法,兼容之前版本 for i in range(2): print(get_time_uuid()) print('---') # 获得随机的uuid for i in range(2): print(get_uuid(udRandom)) print('---')
执行结果:
--- uuid demo --- c8aa92cc-60ef-11e8-aa87-acbf52d15413 c8ab7194-60ef-11e8-b7bd-acbf52d15413 --- c8ab7368-60ef-11e8-996c-acbf52d15413 c8ab741e-60ef-11e8-959d-acbf52d15413 --- 8e108777-26a1-42d6-9c4c-a0c029423eb0 8175a81a-f346-46af-9659-077ad52e3e8f ---
-
fish_common.get_uuid(kind)¶ 获得不重复的 uuid,可以是包含时间戳的 uuid,也可以是完全随机的;基于 Python 的 uuid 类进行封装和扩展;
支持 get_time_uuid() 这样的写法,不需要参数,也可以表示生成包含时间戳的 uuid,兼容 v1.0.12 以及之前版本;
Param: - kind: (int) uuid 类型,整形常量 udTime 表示基于时间戳, udRandom 表示完全随机
返回: - result: (string) 返回类似 66b438e3-200d-4fe3-8c9e-2bc431bb3000 的 uuid
举例如下:
print('--- uuid demo ---') # 获得带时间戳的uuid for i in range(2): print(get_uuid(udTime)) print('---') # 时间戳 uuid 的简单写法,兼容之前版本 for i in range(2): print(get_time_uuid()) print('---') # 获得随机的uuid for i in range(2): print(get_uuid(udRandom)) print('---')
执行结果:
--- uuid demo --- c8aa92cc-60ef-11e8-aa87-acbf52d15413 c8ab7194-60ef-11e8-b7bd-acbf52d15413 --- c8ab7368-60ef-11e8-996c-acbf52d15413 c8ab741e-60ef-11e8-959d-acbf52d15413 --- 8e108777-26a1-42d6-9c4c-a0c029423eb0 8175a81a-f346-46af-9659-077ad52e3e8f ---
-
fish_common.has_space_element(source)¶ 判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组
Param: - source: (list, set, dict) 需要检查的对象
返回: - result: (bool) 存在 None 或空字符串或空格字符串返回 True, 否则返回 False
举例如下:
print('--- has_space_element demo---') print(has_space_element([1, 2, 'test_str'])) print(has_space_element([0, 2])) print(has_space_element([1, 2, None])) print(has_space_element((1, [1, 2], 3, ''))) print(has_space_element({'a': 1, 'b': 0})) print(has_space_element({'a': 1, 'b': []})) print('---')
执行结果:
--- has_space_element demo--- False False True True False True ---
-
fish_common.has_special_char(p_str, check_style=10021)¶ 检查字符串是否含有指定类型字符
Param: - p_str: (string) 需要判断的字符串
- check_style: (string) 需要判断的字符类型,默认为 charChinese (编码仅支持utf-8), 支持 charNum,该参数向后兼容
返回: - True 含有指定类型字符
- False 不含有指定类型字符
举例如下:
print('--- has_special_char demo ---') p_str1 = 'meiyouzhongwen' non_chinese_result = has_special_char(p_str1, check_style=charChinese) print(non_chinese_result) p_str2 = u'有zhongwen' chinese_result = has_special_char(p_str2, check_style=charChinese) print(chinese_result) p_str3 = 'nonnumberstring' non_number_result = has_special_char(p_str3, check_style=charNum) print(non_number_result) p_str4 = 'number123' number_result = has_special_char(p_str4, check_style=charNum) print(number_result) print('---')
执行结果:
--- has_special_char demo --- False True False True ---
-
fish_common.if_json_contain(left_json, right_json, op='strict')¶ 判断一个 json 是否包含另外一个 json 的 key,并且 value 相等;
Param: - left_json: (dict) 需要判断的 json,我们称之为 left
- right_json: (dict) 需要判断的 json,我们称之为 right,目前是判断 left 是否包含在 right 中
- op: (string) 判断操作符,目前只有一种,默认为 strict,向后兼容
返回: - result: (bool) right json 包含 left json 的 key,并且 value 一样,返回 True,否则都返回 False
举例如下:
print('--- json contain demo ---') json1 = {"id": "0001"} json2 = {"id": "0001", "value": "File"} print(if_json_contain(json1, json2)) print('---')
执行结果:
--- json contain demo --- True ---
-
fish_common.join_url_params(dic)¶ 根据传入的键值对,拼接 url 后面 ? 的参数,比如 ?key1=value1&key2=value2
Param: - dic: (dict) 参数键值对
返回: - result: (string) 拼接好的参数
举例如下:
print('--- splice_url_params demo ---') dic1 = {'key1': 'value1', 'key2': 'value2'} print(splice_url_params(dic1)) print('---')
执行结果:
--- splice_url_params demo --- ?key1=value1&key2=value2 ---
-
fish_common.paging(data_list, group_number=1, group_size=10)¶ 获取分组列表数据
Param: - data_list: (list) 需要获取分组的数据列表
- group_number: (int) 分组信息,默认为 1
- group_size: (int) 分组大小,默认为 10
返回: - group_data: (list) 分组数据
举例如下:
print('--- paging demo---') all_records = [1, 2, 3, 4, 5] print(get_group_list_data(all_records)) all_records1 = list(range(100)) print(get_group_list_data(all_records1, group_number=5, group_size=15)) print(get_group_list_data(all_records1, group_number=7, group_size=15)) print('---')
执行结果:
--- paging demo--- [1, 2, 3, 4, 5] [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74] [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] ---
-
fish_common.serialize_instance(obj)¶ 对象序列化
Param: - obj: (object) 对象实例
返回: - obj_dict: (dict) 对象序列化字典
举例如下:
print('--- serialize_instance demo ---') # 定义两个对象 class Obj(object): def __init__(self, a, b): self.a = a self.b = b class ObjB(object): def __init__(self, x, y): self.x = x self.y = y # 对象序列化 b = ObjB('string', [item for item in range(10)]) obj_ = Obj(1, b) print(serialize_instance(obj_)) print('---')
执行结果:
--- serialize_instance demo --- {'__classname__': 'Obj', 'a': 1, 'b': {'__classname__': 'ObjB', 'x': 'string', 'y': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}} ---
-
fish_common.sort_objs_by_attr(objs, key, reverse=False)¶ 对原生不支持比较操作的对象根据属性排序
Param: - objs: (list) 需要排序的对象列表
- key: (string) 需要进行排序的对象属性
- reverse: (bool) 排序结果是否进行反转,默认为 False,不进行反转
返回: - result: (list) 排序后的对象列表
举例如下:
print('--- sorted_objs_by_attr demo---') class User(object): def __init__(self, user_id): self.user_id = user_id users = [User(23), User(3), User(99)] result = sorted_objs_by_attr(users, key='user_id') reverse_result = sorted_objs_by_attr(users, key='user_id', reverse=True) print([item.user_id for item in result]) print([item.user_id for item in reverse_result]) print('---')
执行结果:
--- sorted_objs_by_attr demo--- [3, 23, 99] [99, 23, 3] ---
-
fish_common.sorted_list_from_dict(p_dict, order=10011)¶ 根据字典的 value 进行排序,并以列表形式返回
Param: - p_dict: (dict) 需要排序的字典
- order: (int) 排序规则,odASC 升序,odDES 降序,默认为升序
返回: - o_list: (list) 排序后的 list
举例如下:
print('--- sorted_list_from_dict demo ---') # 定义待处理字典 dict1 = {'a_key': 'a_value', '1_key': '1_value', 'A_key': 'A_value', 'z_key': 'z_value'} print(dict1) # 升序结果 list1 = sorted_list_from_dict(dict1, odASC) print('ascending order result is:', list1) # 降序结果 list1 = sorted_list_from_dict(dict1, odDES) print('descending order result is:', list1) print('---')
执行结果:
--- sorted_list_from_dict demo --- {'a_key': 'a_value', 'A_key': 'A_value', '1_key': '1_value', 'z_key': 'z_value'} ascending order result is: ['1_value', 'A_value', 'a_value', 'z_value'] descending order result is: ['z_value', 'a_value', 'A_value', '1_value'] ---
-
fish_common.yaml_conf_as_dict(file_path, encoding=None)¶ 读入 yaml 配置文件,返回根据配置文件内容生成的字典类型变量
Param: - file_path: (string) 需要读入的 yaml 配置文件长文件名
- encoding: (string) 文件编码
- msg: (string) 读取配置信息
返回: - flag: (bool) 读取配置文件是否正确,正确返回 True,错误返回 False
- d: (dict) 如果读取配置文件正确返回的包含配置文件内容的字典,字典内容顺序与配置文件顺序保持一致
举例如下:
print('--- yaml_conf_as_dict demo---') # 定义配置文件名 conf_filename = 'test_conf.yaml' # 读取配置文件 ds = yaml_conf_as_dict(conf_filename, encoding='utf-8') # 显示是否成功,所有 dict 的内容,dict 的 key 数量 print('flag:', ds[0]) print('dict length:', len(ds[1])) print('msg:', len(ds[1])) print('conf info: ', ds[1].get('tree')) print('---')
执行结果:
--- yaml_conf_as_dict demo--- flag: True dict length: 2 msg: Success conf info: ['README.md', 'requirements.txt', {'hellopackage': ['__init__.py']}, {'test': ['__init__.py']}, {'doc': ['doc.rst']}] ---