社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python的Flask速度慢?用缓存技术加速!

蚂蚁学Python • 4 年前 • 492 次点击  

在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, 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
# speed up calculating Fibonacci numbers with dynamic programming@cached(cache={})def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
# cache least recently used Python Enhancement Proposals@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()
# cache weather data for no longer than ten minutes@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保证答疑)



Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/108682
 
492 次点击