用一行代码将redis用作外部redis
redis-decorator的Python项目详细描述
快速启动
安装
pip install redis_decorator
初始化
fromredis_decimportCachefromredisimportStrictRedisredis=StrictRedis(decode_responses=True)cache=Cache(redis)
示例
确保已启动并运行redis。(https://redis.io/)
示例1:缓存字符串返回
fromtimeimportsleepfromdatetimeimportdatetime@cache.ttl(300)defpseudo_calc():sleep(1)print("Computation in progress")returnstr(datetime.now())foriinrange(10):print(pseudo_calc())
示例2:缓存pandas数据帧
# Set cache's time to live to 300 seconds (expires in 300 seconds)# If left blank, e.g. @cache.df(), cache will stay forever. Don't recommended.importpandasaspd@cache.df(300)defreturn_a_df(*args,**kwargs):sleep(1)print("Computation in progress")returnpd.DataFrame({"time":[str(datetime.now())for_inrange(5)],"foo":list(range(5))})foriinrange(5):print(return_a_df(1,5))
示例3:缓存dict
@cache.dict(60)defreturn_a_dict(*args,**kwargs):sleep(1)print("Computation in progress")return{"now":str(datetime.now())}foriinrange(5):print(return_a_dict())
示例4:缓存浮点数
@cache.float(60)defreturn_a_float(*args,**kwargs):returnrandom()foriinrange(5):print(return_a_float())
删除缓存
# Delete cache by function and signaturecache.delete_cache(return_a_float,2,b=3)# Delete cache by functioncache.delete_cache(return_a_float)# Delete all cachescache.delete_cache()
@cache.dict(60)defreturn_a_dict(*args,**kwargs):sleep(1)print("Computation in progress")return{"now":str(datetime.now())}foriinrange(5):print(return_a_dict())
示例4:缓存浮点数
@cache.float(60)defreturn_a_float(*args,**kwargs):returnrandom()foriinrange(5):print(return_a_float())
删除缓存
# Delete cache by function and signaturecache.delete_cache(return_a_float,2,b=3)# Delete cache by functioncache.delete_cache(return_a_float)# Delete all cachescache.delete_cache()