Skip to content

Instantly share code, notes, and snippets.

@gaoconghui
Last active June 13, 2018 08:20
Show Gist options
  • Save gaoconghui/e210010b0a3575b5c6d474a4e0b62da8 to your computer and use it in GitHub Desktop.
Save gaoconghui/e210010b0a3575b5c6d474a4e0b62da8 to your computer and use it in GitHub Desktop.
一些常用的方法
# -*- coding: utf-8 -*-
def ensure_unicode(s):
if not s:
return s
if isinstance(s, unicode):
return s
elif isinstance(s, str):
return s.decode('utf-8')
else:
return s
def ensure_utf8(s):
if not s:
return s
if isinstance(s, str):
return s
elif isinstance(s, unicode):
return s.encode('utf-8')
else:
return s
def retry_ignore(retry_times=3, error_return=None):
"""
重试一个方法若干次,如果都报错则返回需要的结果(默认返回或者抛出错误)
:param retry_times: 重试次数
:param error_return: 都出错时的返回值,None为抛出错误
:return:
"""
def decorate(func):
@wraps(func)
def inner(*args, **kwargs):
for i in range(retry_times):
try:
return func(*args, **kwargs)
except Exception as e:
logger.exception(e)
if i == retry_times - 1 and error_return is None:
raise e, None, sys.exc_info()[2]
else:
logger.exception(e)
if error_return:
return error_return
return inner
return decorate
_cache = {}
def cache_me(func):
"""
缓存,会以str(func)以及参数的str方法的返回作为key
存在一个问题,当参数str方法返回内容一致时缓存会错误
:param func:
:return:
"""
@wraps(func)
def inner(*args, **kwargs):
key = "{func}_{args}_{kwargs}".format(func=str(func), args=str(args), kwargs=str(kwargs))
key = hashlib.md5(key).hexdigest()
if key not in _cache:
_cache[key] = func(*args, **kwargs)
return _cache[key]
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment