Python的Flask速度慢?用缓存技术加速!
在Web服务中,使用缓存是一种加速程序运行的重要技术。
这是因为,不同的存储介质,是有速度上很大的差异的,比如一个Web服务会使用典型的三级存储技术:
MySQL:底层数据存储,保证数据的准确一致性;
Redis:缓存第一层,分布式内存数据库,比MySQL快很多;
本地缓存:就是在Web服务本地内存中缓存,速度更快;
本文介绍Python程序怎样在本地内存缓存数据的方法,介绍两种方式:
方法1:使用Python自带的functools.lru_cache
但是functools.lru_cache不支持按时间的过期,比如5秒钟缓存生效重新拉取,因此进行如下的改造:
把这个代码放到一个文件里
from functools import lru_cache, wrapsfrom datetime import datetime, timedeltadef 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.lifetimereturn func(*args, **kwargs)return wrapped_funcreturn wrapper_cache
使用起来很简单了:
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# speed up calculating Fibonacci numbers with dynamic programmingdef fib(n):return n if n < 2 else fib(n - 1) + fib(n - 2)# cache least recently used Python Enhancement Proposalsdef get_pep(num):url = 'http://www.python.org/dev/peps/pep-%04d/' % numwith urllib.request.urlopen(url) as s:return s.read()# cache weather data for no longer than ten minutesdef get_weather(place):return owm.weather_at_place(place).get_weather()
这个模块的地址:https://github.com/tkem/cachetools
最后,欢迎关注我的全天视频系列(购买加VX保证答疑)

评论
