在Web服务中,使用缓存是一种加速程序运行的重要技术。
这是因为,不同的存储介质,是有速度上很大的差异的,比如一个Web服务会使用典型的三级存储技术:
本文介绍Python程序怎样在本地内存缓存数据的方法,介绍两种方式:
方法1:使用Python自带的functools.lru_cache
但是functools.lru_cache不支持按时间的过期,比如5秒钟缓存生效重新拉取,因此进行如下的改造:
把这个代码放到一个文件里
from functools import lru_cache, wrapsfrom datetime import datetime, timedelta
def timed_lru_cache(seconds: int, maxsize: int = 128): def wrapper_cache(func): func = lru_cache(maxsize=maxsize)(func) func.lifetime = timedelta(seconds=seconds) func.expiration = datetime.utcnow() + func.lifetime
@wraps(func) def wrapped_func(*args, **kwargs): if datetime.utcnow() >= func.expiration: func.cache_clear() func.expiration = datetime.utcnow() + func.lifetime
return func(*args, **kwargs)
return wrapped_func
return wrapper_cache
使用起来很简单了:
@timed_lru_cache(10)def get_article_from_server(url): print("Fetching article from server...") response = requests.get(url) return response.text
这样的话,每次调用这个函数,会先获取本地内存的数据,如果取不到或者10秒钟过期,才会取真正的请求外部数据。
方法2:使用开源模块cachetools
直接使用就可以,更加简单:
from cachetools import cached, LRUCache, TTLCache
@cached(cache={})def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
@cached(cache=LRUCache(maxsize=32))def get_pep(num): url = 'http://www.python.org/dev/peps/pep-%04d/' % num with urllib.request.urlopen(url) as s: return s.read()
@cached(cache=TTLCache(maxsize=1024, ttl=600))def get_weather(place): return owm.weather_at_place(place).get_weather()
这个模块的地址:https://github.com/tkem/cachetools
最后,欢迎关注我的全天视频系列(购买加VX保证答疑)
