[Python]使用Decorator设计Cache
来源:互联网 发布:阿里云ecs和vps区别 编辑:程序博客网 时间:2024/05/03 16:59
直接上源码:
#!/usr/bin/env python# -*- coding: utf-8 -*-"""Created on 4/20/16@author: Jiezhi.G@gmail.comMy Blog: jiezhi.github.ioReference: <Expert Python Programming> Chapter 2--Decorators_Proxy Page.53"""import timeimport hashlibimport picklecache = {}def is_obsolete(entry, duration): return time.time() - entry['time'] > durationdef compute_key(function, args, kw): key = pickle.dumps((function.func_name, args, kw)) return hashlib.sha1(key).hexdigest()def memoize(duration=10): def _memoize(function): def __memoize(*args, **kw): key = compute_key(function, args, kw) # do we have it already? if key in cache and not is_obsolete(cache[key], duration): print 'we got a winner' return cache[key]['value'] # computing result = function(*args, **kw) # storing the result cache[key] = {'value': result, 'time': time.time()} return result return __memoize return _memoize@memoize()def very_very_very_complex_stuff(a, b): return a + bif __name__ == '__main__': print very_very_very_complex_stuff(2, 2) print cache print very_very_very_complex_stuff(2, 2)
运行后可以看到结果:
4{'dedfca39c250ca2047c5d66a13c5df2e9ac90181': {'value': 4, 'time': 1461155366.249486}}we got a winner4
0 0
- [Python]使用Decorator设计Cache
- Python:decorator的使用
- Python的decorator使用
- Python装饰器 decorator 设计模式
- 设计模式-装饰模式-decorator-python
- 使用Decorator设计模式增强request对象
- 使用Python Decorator实现数据驱动测试
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- Python decorator
- python decorator
- python decorator
- Python Decorator
- Python Decorator
- python decorator
- hdu 2159
- c#winfrom PropertyGrid 运行时变更属性项
- 迷你DVD管理器,尽量缩短代码长度!!!
- 大数相加方法------3
- bzoj 2461: [BeiJing2011]符环
- [Python]使用Decorator设计Cache
- JVM调优总结-典型配置举例2
- RHEL7安装部署RabbitMQ
- SMTP协议
- django缓存优化 Database 缓存解析
- C语言初级的小程序
- JS循环
- Java 8 Stream
- redis© on write