[python]缓存函数结果进redis
工作中遇到一个问题,就是有一些需要对数据库做全表扫描,而且对结果要求比较宽松的地方,总觉得可以找地方优化,比如暂时保存计算结果。
首先想起来的就是functools.lru_cache,但是可惜在python2.7中没有这个装饰器。
然后就是在stackoverflow找了一个:
(来源:https://stackoverflow.com/questions/11815873/memoization-library-for-python-2-7)
import time
import functools
import collections def lru_cache(maxsize = 255, timeout = None):
"""lru_cache(maxsize = 255, timeout = None) --> returns a decorator which returns an instance (a descriptor). Purpose - This decorator factory will wrap a function / instance method and will supply a caching mechanism to the function.
For every given input params it will store the result in a queue of maxsize size, and will return a cached ret_val
if the same parameters are passed. Params - maxsize - int, the cache size limit, anything added above that will delete the first values enterred (FIFO).
This size is per instance, thus 1000 instances with maxsize of 255, will contain at max 255K elements.
- timeout - int / float / None, every n seconds the cache is deleted, regardless of usage. If None - cache will never be refreshed. Notes - If an instance method is wrapped, each instance will have it's own cache and it's own timeout.
- The wrapped function will have a cache_clear variable inserted into it and may be called to clear it's specific cache.
- The wrapped function will maintain the original function's docstring and name (wraps)
- The type of the wrapped function will no longer be that of a function but either an instance of _LRU_Cache_class or a functool.partial type. On Error - No error handling is done, in case an exception is raised - it will permeate up.
""" class _LRU_Cache_class(object):
def __init__(self, input_func, max_size, timeout):
self._input_func = input_func
self._max_size = max_size
self._timeout = timeout # This will store the cache for this function, format - {caller1 : [OrderedDict1, last_refresh_time1], caller2 : [OrderedDict2, last_refresh_time2]}.
# In case of an instance method - the caller is the instance, in case called from a regular function - the caller is None.
self._caches_dict = {} def cache_clear(self, caller = None):
# Remove the cache for the caller, only if exists:
if caller in self._caches_dict:
del self._caches_dict[caller]
self._caches_dict[caller] = [collections.OrderedDict(), time.time()] def __get__(self, obj, objtype):
""" Called for instance methods """
return_func = functools.partial(self._cache_wrapper, obj)
return_func.cache_clear = functools.partial(self.cache_clear, obj)
# Return the wrapped function and wraps it to maintain the docstring and the name of the original function:
return functools.wraps(self._input_func)(return_func) def __call__(self, *args, **kwargs):
""" Called for regular functions """
return self._cache_wrapper(None, *args, **kwargs)
# Set the cache_clear function in the __call__ operator:
__call__.cache_clear = cache_clear def _cache_wrapper(self, caller, *args, **kwargs):
# Create a unique key including the types (in order to differentiate between 1 and '1'):
kwargs_key = "".join(map(lambda x : str(x) + str(type(kwargs[x])) + str(kwargs[x]), sorted(kwargs)))
key = "".join(map(lambda x : str(type(x)) + str(x) , args)) + kwargs_key # Check if caller exists, if not create one:
if caller not in self._caches_dict:
self._caches_dict[caller] = [collections.OrderedDict(), time.time()]
else:
# Validate in case the refresh time has passed:
if self._timeout != None:
if time.time() - self._caches_dict[caller][1] > self._timeout:
self.cache_clear(caller) # Check if the key exists, if so - return it:
cur_caller_cache_dict = self._caches_dict[caller][0]
if key in cur_caller_cache_dict:
return cur_caller_cache_dict[key] # Validate we didn't exceed the max_size:
if len(cur_caller_cache_dict) >= self._max_size:
# Delete the first item in the dict:
cur_caller_cache_dict.popitem(False) # Call the function and store the data in the cache (call it with the caller in case it's an instance function - Ternary condition):
cur_caller_cache_dict[key] = self._input_func(caller, *args, **kwargs) if caller != None else self._input_func(*args, **kwargs)
return cur_caller_cache_dict[key] # Return the decorator wrapping the class (also wraps the instance to maintain the docstring and the name of the original function):
return (lambda input_func : functools.wraps(input_func)(_LRU_Cache_class(input_func, maxsize, timeout)))
但是会出现一个问题,那就是以后部署的话,会有多个服务器部署在nginx后面,但是这些缓存结果是保存在单个服务器的,那么就会在不同的请求结果就可能出现不一致,那么怎么办?
放进redis?
然后就想起来了flask-cache,但是可惜,如果用这个缓存普通函数的计算结果会报错。
最后,只能自己动手写一个了:
def cache_func_redis(timeout=100):
def decorator(func):
@wraps(func)
def wrapper(*args,**kwargs):
lst_dct = sorted([{k: kwargs[k]} for k in kwargs], key=lambda d:d.keys()[0])
lst = [str(d.values()[0]) for d in lst_dct]
k = ''.join([func.__name__, str(args), ''.join(lst)])
r = redis.Redis(connection_pool=cache_redis)
d = r.get(k)
if d:
res = json.loads(d)['res']
return res
res = func(*args, **kwargs)
d = json.dumps({
'res': res
})
r.set(k, d)
r.expire(k, timeout)
return res
return wrapper
return decorator
利用函数名和传入的参数,提取特征值作为redis中存入的名字,把计算结果存入redis,失效时间为timeout,但是需要注意的是,
*如果传入的参数为字典,那么可能不会被命中
*被缓存的结果必须为对准确性时效性要求不高的地方
*被缓存的结果应该为基本的python数据结构,否则可能会报错
*还没有做压力测试,等做了压力测试把结果传上来
参考资料:
https://github.com/python/cpython/blob/3.4/Lib/functools.py
https://stackoverflow.com/questions/11815873/memoization-library-for-python-2-7
[python]缓存函数结果进redis的更多相关文章
- 缓存系列之四:redis持久化与redis主从复制
一:redis 虽然是一个内存级别的缓存程序,即redis 是使用内存进行数据的缓存的,但是其可以将内存的数据按照一定的策略保存到硬盘上,从而实现数据持久保存的目的,redis支持两种不同方式的数据持 ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- 阿里云Centos7.6上面部署基于redis的分布式爬虫scrapy-redis将任务队列push进redis
Scrapy是一个比较好用的Python爬虫框架,你只需要编写几个组件就可以实现网页数据的爬取.但是当我们要爬取的页面非常多的时候,单个服务器的处理能力就不能满足我们的需求了(无论是处理速度还是网络请 ...
- Python之函数进阶
本节内容 上一篇中介绍了Python中函数的定义.函数的调用.函数的参数以及变量的作用域等内容,现在来说下函数的一些高级特性: 递归函数 嵌套函数与闭包 匿名函数 高阶函数 内置函数 总结 一.递归函 ...
- python基础—函数装饰器
python基础-函数装饰器 1.什么是装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能. 装饰器的返回值是也是一个函数对象. 装饰器经常用于有切 ...
- 【转】Python之函数进阶
[转]Python之函数进阶 本节内容 上一篇中介绍了Python中函数的定义.函数的调用.函数的参数以及变量的作用域等内容,现在来说下函数的一些高级特性: 递归函数 嵌套函数与闭包 匿名函数 高阶函 ...
- Python 全栈开发四 python基础 函数
一.函数的基本语法和特性 函数的定义 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的.函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数 ...
- Python int() 函数
Python int() 函数 Python 内置函数 描述 int() 函数用于将一个字符串或数字转换为整型. 语法 以下是 int() 方法的语法: class int(x, base=10) ...
- Python oct() 函数
Python oct() 函数 Python 内置函数 描述 oct() 函数将一个整数转换成8进制字符串. 语法 oct 语法: oct(x) 参数说明: x -- 整数. 返回值 返回8进制字符 ...
随机推荐
- UNIX环境高级编程 第6章 系统数据文件和信息
UNIX系统的正常运作需要用到大量与系统有关的数据文件,例如系统用户账号.用户密码.用户组等文件.出于历史原因,这些数据文件都是ASCII文本文件,并且使用标准I/O库函数来读取. 口令文件 /etc ...
- python端口扫描
简易版: #author:Blood_Zero #coding:utf-8 import socket import sys PortList=[21,22,23,25,80,135] # host= ...
- 对接微信支付使用HMAC-SHA256使用签名算法实现方式
最近做微信押金支付对接,很多坑,心累!这里提醒一下各位: 首先,确保自己商户号进了白名单,没有需要联系客服,否则接口是调不通的,会一直提示参数错误 其次,确保接口文档是最新的,最好去官网去看,否则可能 ...
- 一个简单的java jdbc案例
有些时候,配置一个spring+mybatis框架,然后写xml,dao ,service显得特别繁琐. 如果我们只是想查一下数据库,不考虑连接复用也不考虑动态sql,可以用原生的jdbc来实现,方便 ...
- java 面试算法题
/** * 设有n个人依围成一圈,从第1个人开始报数,数到第m个人出列,然后从 * 出列的下一个人开始报数,数到第m个人又出列,…,如此反复到所有的人全部出列为 * 止.设n个人的编号分别为1,2,… ...
- aarch64_m1
MAKEDEV-3.24-18.fc26.aarch64.rpm 2017-02-14 08:46 99K fedora Mirroring Project MUMPS-5.0.2-8.fc26.aa ...
- MVVM模式用依赖注入的方式配置ViewModel并注册消息
最初的想法 这次主要讨论下给View指定ViewModel的事情.一般来说给View指定ViewModel常用的方式有两种,一种是在View的后台代码中写DataContext = new ViewM ...
- linux终端操作快捷键
终端操作快捷键: 新建家目录下终端窗口:Ctrl+Alt+t在当期当前路径下新建终端窗口:Ctrl+Shift+n退出终端窗口:Ctrl+Shift+q 多个终端窗口之间相互切换:Tab+Alt 终端 ...
- AdvStringGrid 标题头
标题头内容: 字体: 标题头高度: 头的对齐方式:
- 用SQL语句添加删除修改字段、一些表与字段的基本操作、数据库备份等
用SQL语句添加删除修改字段 1.增加字段 alter table docdsp add dspcode char(200) 2.删除字段 ALTER TABLE table_NAME DROP CO ...