常用模块主要分为以下几类(缺失的后续再补充):时间转换
时间计算
序列化和反序列化:json,pickle
编解码:unicode,base64
加解密:md5,sha1,hmac_sha1,aes
常见装饰器:计算执行时间装饰器
缓存装饰器
错误重试装饰器
延迟装饰器
尾递归优化装饰器
ini配置文件读取
代码整合如下:#!/usr/bin/env python# -*- coding: utf-8 -*-"""
Created on 9/21/17 1:46 PM
@author: Chen Liang
@function: python常用模块集锦,util.py
"""import timeimport datetimeimport ConfigParserimport astimport sysimport jsonimport pickleimport base64import hashlibfrom Crypto.Cipher import AESfrom binascii import b2a_hex, a2b_hexfrom functools import wraps
BEFORE = 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 = args
self.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 @staticmethod