常用模块主要分为以下几类(缺失的后续再补充):

  • 时间转换
  • 时间计算
  • 序列化和反序列化:jsonpickle
  • 编解码:unicodebase64
  • 加解密:md5sha1hmac_sha1aes
  • 常见装饰器:
    • 计算执行时间装饰器
    • 缓存装饰器
    • 错误重试装饰器
    • 延迟装饰器
    • 尾递归优化装饰器
  • ini配置文件读取

代码整合如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
Created on 9/21/17 1:46 PM
@author: Chen Liang
@function: python常用模块集锦,util.py
"""import time
import datetime
import ConfigParser
import ast
import sys
import json
import pickle
import base64
import hashlib
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from functools import wrapsBEFORE = 1
LATER = 2class CommonUtil(object):"""Python通用单元:不好归类但常用的方法此处添加"""passclass TimeTransferUtil(object):"""时间相关的常见转换方法"""class TimeUtil(object):"""时间相关的常见计算方法"""@staticmethoddef str_to_date():passclass SerializeUtil(object):"""序列化和反序列化:json, pickle"""@staticmethoddef json_loads(json_str, encoding=None):try:obj = json.loads(s=json_str, encoding=encoding)return True, objexcept ValueError as e:return False, str(e)except Exception as e:return False, str(e)@staticmethoddef json_dumps(obj):try:json_str = json.dumps(obj=obj)return True, json_strexcept TypeError as e:return False, str(e)except Exception as e:return False, str(e)@staticmethoddef pickle_loads(pickle_str):try:obj = pickle.loads(pickle_str)return True, objexcept IndexError as e:return False, str(e)except Exception as e:return False, str(e)@staticmethoddef pickle_dumps(obj):try:pickle_str = pickle.dumps(obj)return True, pickle_strexcept Exception as e:return False, str(e)class CodecUtil(object):"""编解码相关常见方法:base64 unicode"""@staticmethoddef base64_encode(data):try:return True, base64.b64encode(data)except TypeError as e:return False, str(e)except Exception as e:return False, str(e)@staticmethoddef base64_decode(encoded_data):try:return True, base64.b64decode(encoded_data)except TypeError as e:return False, str(e)except Exception as e:return False, str(e)@staticmethoddef to_unicode(s, encoding='utf-8'):return s if isinstance(s, unicode) else unicode(s, encoding)@staticmethoddef unicode_to(unicode_s, encoding='utf-8'):return unicode_s.encode(encoding)class CryptoUtil(object):"""加解密相关常见方法: md5 aes"""@staticmethoddef md5(str_object):"""md5"""m = hashlib.md5()m.update(str_object)return m.hexdigest()@staticmethoddef aes_encrypt(s, key, salt, mode=AES.MODE_CBC):"""aes加密:param s: 待加密字符串:param key: 密钥:param salt: 盐, 16bit eg. b'0000000101000000':param mode: AES模式:return: 加密后的字符串"""cipher = AES.new(hashlib.md5(key).hexdigest(), mode, salt)n_text = s + ('\0' * (16 - (len(s) % 16)))return b2a_hex(cipher.encrypt(n_text))@staticmethoddef aes_decrypt(s, key, salt, mode=AES.MODE_CBC):"""aes解密:param s: 待解密字符串:param key: 密钥:param salt: 盐, 16bit eg. b'0000000101000000':param mode: AES模式:return: 解密后的字符串"""cipher = AES.new(hashlib.md5(key).hexdigest(), mode, salt)return cipher.decrypt(a2b_hex(s)).rstrip('\0')class TailRecurseException:"""尾递归异常"""def __init__(self, args, kwargs):self.args = argsself.kwargs = kwargsclass DecoratorUtil(object):"""常见装饰器: 执行时间timeit,缓存cache,错误重试retry"""__cache_dict = {}@staticmethoddef timeit(fn):"""计算执行时间"""@wraps(fn)def wrap(*args, **kwargs):start = time.time()ret = fn(*args, **kwargs)end = time.time()print "@timeit: {0} tasks, {1} secs".format(fn.__name__, str(end - start))return retreturn wrap@staticmethoddef __is_expired(entry, duration):"""是否过期"""if duration == -1:return Falsereturn time.time() - entry['time'] > duration@staticmethoddef __compute_key(fn, args, kw):"""序列化并求其哈希值"""key = pickle.dumps((fn.__name__, args, kw))return hashlib.sha1(key).hexdigest()@classmethoddef cache(cls, expired_time=-1):"""缓存:param expired_time: 过期时间,-1 表示不过期:return: 返回缓存的结果或者计算的结果"""def _cache(fn):@wraps(fn)def wrap(*args, **kwargs):key = cls.__compute_key(fn, args, kwargs)if key in cls.__cache_dict:if cls.__is_expired(cls.__cache_dict[key], expired_time) is False:return cls.__cache_dict[key]['value']ret = fn(*args, **kwargs)cls.__cache_dict[key] = {'value': ret,'time': time.time()}return retreturn wrapreturn _cache@staticmethoddef retry(exceptions, retry_times=3, time_pause=3, time_offset=1):"""错误重试:param exceptions: 单个异常比如ValueError, 或者tuple,元组元素是异常,比如(ValueError, TypeError):param retry_times: 重试次数:param time_pause: 初始暂停时间:param time_offset: 暂停时间的偏移倍数,默认不偏移:return: 返回成功的值,或者重拾次数结束时抛出异常"""def _retry(fn):@wraps(fn)def wrap(*args, **kwargs):retry_times_tmp, time_pause_tmp = retry_times, time_pausewhile retry_times_tmp > 1:try:return fn(*args, **kwargs)except exceptions:time.sleep(time_pause_tmp)retry_times_tmp -= 1time_pause_tmp *= time_offsetreturn fn(*args, **kwargs)return wrapreturn _retry@staticmethoddef delay(delay_time=3, mode=BEFORE):"""延迟装饰器,支持在函数执行之前和之后加延时,如果想在前后同时加,可以使用两次装饰。time.sleep只会阻塞当前线程不会阻塞整个进程,其它线程不受影响:param delay_time: 延迟时间,是float类型:param mode: 模式,指定是在函数执行之前加延时还是在执行之后加,值为BEFORE(1)或者LATER(2):return:"""def _delay(fn):@wraps(fn)def wrap(*args, **kwargs):if mode == BEFORE:time.sleep(delay_time)ret = fn(*args, **kwargs)if mode == LATER:time.sleep(delay_time)return retreturn wrapreturn _delay@staticmethoddef tail_call_optimized(fn):"""尾递归优化装饰器,如果被装饰函数不是尾递归函数则会报错"""@wraps(fn)def wrap(*args, **kwargs):f = sys._getframe()if f.f_back and f.f_back.f_back and f.f_back.f_back.f_code == f.f_code:raise TailRecurseException(args, kwargs)else:while True:try:return fn(*args, **kwargs)except TailRecurseException as e:args = e.argskwargs = e.kwargsreturn wrapclass IniConfigParserUtil(object):"""ini配置文件读取"""def __init__(self, *file_names):"""init:param file_names: 包含多个元素的可迭代对象"""self.config = ConfigParser.ConfigParser()for file_name in file_names:try:self.config.readfp(open(file_name, 'rb'))breakexcept IOError:continueelse:sys.exit('All files have failed to read')def get_string(self, section, option):return self.config.get(section, option)def get_int(self, section, option):return self.config.getint(section, option)def get_float(self, section, option):return self.config.getfloat(section, option)def get_boolean(self, section, option):return self.config.getboolean(section, option)def get_list(self, section, option):return ast.literal_eval(self.config.get(section, option))def get_dict(self, section, option):return ast.literal_eval(self.config.get(section, option))
复制代码

缺失部分后续待添加,记得填坑。

本文首发于python黑洞网,csdn同步跟新

Python常用模块集锦相关推荐

  1. python常用模块大全总结-常用python模块

    广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品.未来,我们一起乘风破浪,创造无限可能. python常用模块什么是模块? 常见的场景:一个模块就是一个包含了py ...

  2. 实战篇一 python常用模块和库介绍

    # -_-@ coding: utf-8 -_-@ -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = ...

  3. 对于python来说、一个模块就是一个文件-python常用模块

    python常用模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用pyt ...

  4. python常用模块之shelve模块

    python常用模块之shelve模块 shelve模块是一个简单的k,v将内存中的数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据类型 我们在上面讲json.pickle ...

  5. Python常用模块——目录

    Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...

  6. Python+常用模块(2).md

    Python 常用模块 1. random模块 1.1 导入模块 import random 1.2 random.random() 生成一个从0到1的随机浮点数 1.3 random.uniform ...

  7. python用什么来写模块-Python常用模块——模块介绍与导入

    Python常用模块--模块介绍与导入 一.什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分 ...

  8. Python 常用模块总结

    Python 常用模块总结 1.random 2.math 3.os 4.os.path 5.sys 6.hashlib 7.hmac 8.time 9.datetime 10.calendar 11 ...

  9. python常用模块-调用系统命令模块(subprocess)

    python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...

最新文章

  1. threeJS 中数学相关内容
  2. iOS开发小知识之正则表达式的简单用法
  3. 转: 回车(CR)与换行(LF), '\r'和'\n'的区别
  4. 查看linux的用户 7.2,linux下查看用户登入系统相关命令及编写脚本(七)
  5. PostgreSQL学习手册(数据库维护) 转
  6. 计组之中央处理器:4、硬布线控制器的原理与设计
  7. MVC HtmlHelper扩展——实现分页功能
  8. 再见,中关村“金三角”!
  9. python元类_Python中元类
  10. 随手记---Pharming
  11. hdoj6298:Maximum Multiple(找规律,总结)
  12. 集体智慧编程--优化
  13. python语言基础与应用 mooc答案_Python语言基础与应用_中国大学 MOOC_章节考试选修课答案...
  14. 胎压检测c语言pta,汽车胎压检测系统的设计与实现
  15. html短竖线符号,word竖线符号
  16. 华为路由器hilink怎么用_荣耀路由HiLink怎么实现一键组网?
  17. xp下的资源管理器界面上的前进后退等图标保持在系统哪里?shell32.dll里没有。
  18. android 锁屏 浮动窗口,Android如何实现锁屏状态下弹窗
  19. Onvif协议学习:14、球机云台控制PTZ
  20. powershell 报错 0xffff0000 的解决方法

热门文章

  1. 在3.5下实现无配置WCF服务
  2. Hive常见的存储格式文件比较
  3. python sqlalchemy orm
  4. (43)VHDL实现译码器与解码器
  5. (60)Verilog HDL测试激励:复位激励1
  6. 5.FreeRTOS学习笔记- 互斥量
  7. I2C 协议分析和学习
  8. 【C语言】qsort函数用法(转)
  9. 电脑cpu风扇转一下就停无法开机_电脑无法正常开机风扇转一下就停的原因及解决方法...
  10. pthread_mutex_init函数《代码》