Python常用模块合集常用模块主要分为以下几类(遗漏的稍后补上):时间转换时间计算序列化与反序列化:json,pickle编解码:unicode,base64加解密:md5,sha1、hmac_sha1、aes常用装饰器:计算执行时间装饰器缓存装饰器错误重试装饰器延迟装饰器尾递归优化装饰器ini配置文件读取代码集成如下:#!/usr/bin/envpython#-*-编码:utf-8-*-"""创建于9/21/171:46PM@作者:陈亮@function:常用python模块集合,util.py"""importtimeimportdatetimeimportConfigParserimportasimportsysimportjsonimportpickleimportbase64importhashlibfromCrypto.CipherimportAESfrombinasciiimportb2a_hex,a2b_hexfromfunctoolsimportwrapsBEFORE=1LATER=2classCommonUtil(object):类中常用的方法"""Python添加这里"""passclassTimeTransferUtil(object):"""时间相关的常用转换方法"""classTimeUtil(object):"""时间相关的常用计算方法"""@staticmethoddefstr_to_date():passclassSerializeUtil(object):"""序列化和反序列化:json,pickle"""@staticmethoddefjson_loads(json_str,encoding=None):try:obj=json.loads(s=json_str,encoding=encoding)returnTrue,objexceptValueErrorase:returnFalse,str(e)exceptExceptionase:returnFalse,str(e)@staticmethoddefjson_dumps(obj):try:json_str=json.dumps(obj=obj)返回真,json_str除了TypeError作为e:返回False,str(e)除了Exception作为e:returnFalse,str(e)@staticmethoddefpickle_loads(pickle_str):try:obj=pickle.loads(pickle_str)returnTrue,obj除了IndexErrorase:returnFalse,str(e)exceptExceptionase:returnFalse,str(e)@staticmethoddefpickle_dumps(obj):try:pickle_str=pickle.dumps(obj)returnTrue,pickle_strexceptExceptionase:返回False,str(e)classCodecUtil(object):"""编写解码相关常见方法:base64unicode"""@staticmethoddefbase64_encode(data):尝试:返回True,base64.b64encode(data)除了TypeError为e:返回False,str(e)除了Exception为e:返回False,str(e)@staticmethoddefbase64_decode(encoded_data):尝试:返回True,base64。b64decode(encoded_data)除了TypeError为e:returnFalse,str(e)除了Exception为e:returnFalse,str(e)@staticmethoddefto_unicode(s,encoding='utf-8'):returnsifisinstance(s,unicode)elseunicode(s,encoding)@staticmethoddefunicode_to(unicode_s,encoding='utf-8'):returnunicode_s.encode(encoding)classCryptoUtil(object):"""加解密相关常见方法:md5aes"""@staticmethoddefmd5(str_object):"""md5"""m=hashlib.md5()m.update(str_object)returnm.hexdigest()@staticmethoddefaes_encrypt(s,key,salt,mode=AES.MODE_CBC):"""aes加密:params:要加密的字符串:paramkey:key:paramsalt:salt,16bit例如。b'0000000101000000':parammode:AESmode:return:encryptedstring"""cipher=AES.new(hashlib.md5(key).hexdigest(),mode,salt)n_text=s+('\0'*(16-(len(s)%16)))returnb2a_hex(cipher.encrypt(n_text))@staticmethoddefaes_decrypt(s,key,salt,mode=AES.MODE_CBC):"""aes解密:参数s:字符串待解密:paramkey:key:paramsalt:salt,16bit例如。b'0000000101000000':parammode:AESmode:return:Decryptedstring"""cipher=AES.new(hashlib.md5(key).hexdigest(),mode,salt)returncipher.decrypt(a2b_hex(s)).rstrip('\0')classTailRecurseException:"""尾递归异常"""def__init__(self,args,kwargs):self.args=argsself.kwargs=kwargsclassDecoratorUtil(object):"""普通装饰器:执行时间timeit,缓存,错误重试重试"""__cache_dict={}@staticmethoddeftimeit(fn):"""计算执行时间"""@wraps(fn)defwrap(*args,**kwargs):start=time.time()ret=fn(*args,**kwargs)end=time.time()print"@timeit:{0}任务,{1}secs".format(fn.__name__,str(end-start))returnretreturnwrap@staticmethoddef__is_expired(entry,duration):"""Expired"""ifduration==-1:returnFalsereturntime.time()-entry['time']>duration@staticmethoddef__compute_key(fn,args,kw):"""序列化并散列它"""key=pickle.dumps((fn.__name__,args,kw))returnhashlib.sha1(key).hexdigest()@classmethoddefcache(cls,expired_time=-1):"""cache:paramexpired_time:过期时间,-1表示没有过期:return:返回缓存或计算结果"""def_cache(fn):@wraps(fn)defwrap(*args,**kwargs):key=cls.__compute_key(fn,args,kwargs)ifkeyincls.__cache_字典:如果cls.__is_expired(cls.__cache_dict[key],expired_time)为假:返回cls.__cache_dict[key]['v??alue']ret=fn(*args,**kwargs)cls.__cache_dict[key]={'value':ret,'time':time.time()}returnretreturnwrapreturn_cache@staticmethoddefretry(exceptions,retry_times=3,time_pause=3,time_offset=1):"""errorretry:param异常:单个异常如ValueError,或者元组,元组元素是异常,如(ValueError,TypeError):paramretry_times:重试次数:paramtime_pause:初始暂停时间:paramtime_offset:暂停时间的偏移倍数,默认unbiasedShift:return:返回一个成功的值,或者在重试次数结束时抛出异常"""def_retry(fn):@wraps(fn)defwrap(*args,**kwargs):retry_times_tmp,time_pause_tmp=retry_times,time_pause当retry_times_tmp>1时:尝试:返回fn(*args,**kwargs)除了异常:time.sleep(time_pause_tmp)retry_times_tmp-=1time_pause_tmp*=time_offsetreturnfn(*args,**kwargs)returnwrapreturn_retry@staticmethoddefdelay(delay_time=3、mode=BEFORE):"""延时装饰器,支持在函数执行前后添加延时,如果要前后添加延时,可以使用两个装饰器time.sleep只会阻塞当前线程,不会阻塞整个进程,其他线程不受影响:paramdelay_time:延迟时间,为float类型:parammode:模式,指定是在函数执行前还是执行后加延迟,值为BEFORE(1)或LATER(2):return:"""def_delay(fn):@wraps(fn)defwrap(*args,**kwargs):ifmode==BEFORE:time.sleep(delay_time)ret=fn(*args,**kwargs)ifmode==LATER:time.sleep(delay_time)returnretreturnwrapreturn_delay@staticmethoddeftail_call_optimized(fn):"""尾递归优化装饰器,如果装饰的话If该函数不是尾递归函数,会报错"""@wraps(fn)defwrap(*args,**kwargs):f=sys._getframe()iff.f_backandf.f_back.f_back和f.f_back.f_back.f_code==f.f_code:raiseTailRecurseException(args,kwargs)else:whileTrue:try:returnfn(*args,**kwargs)除了TailRecurseExceptionase:args=e.argskwargs=e.kwargsreturnwrapclassIniConfigParserUtil(object):"""ini配置文件读取"""def__init__(self,*file_names):"""init:paramfile_names:包含多个元素的可替代对象"""self.config=ConfigParser.ConfigParser()forfile_nameinfile_names:try:self.config.readfp(open(file_name,'rb'))breakexceptIOError:continueelse:sys.exit('所有文件读取失败')defget_string(self,section,option):returnself.config.get(section,option)defget_int(self,section,option):returnself.config.getint(部分,选项)defget_float(self,部分,选项):返回self.config.getfloat(部分,选项)defget_boolean(self,部分,选项):返回self.config.getboolean(部分,选项)defget_list(self,section,option):returnast.literal_eval(self.config.get(section,option))defget_dict(self,section,option):returnast.literal_eval(self.config.get(section),option))漏掉的部分稍后补上,记得补坑记得点个赞哦!对计算机各个方向的视频课程和电子书,从入门、进阶、实用进行了认真梳理,并按照目录进行合理分类。你总能找到你需要的学习资料。你在等什么?立即关注并下载!!!念念不忘,必有回响,朋友们,请点个赞,万分感谢。我是职场亮哥,四年工作经验的YY高级软件工程师,拒绝当领导的斜杠程序员。听我说,我进步很大。如果有幸帮到你,请给我一个【点赞】,给我一个关注,如能评论鼓励,将不胜感激。职场凉阁文章列表:更多文章我的所有文章和回答均与版权保护平台合作,版权归职场凉阁所有。未经授权转载必究!
