[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进制字符 ...
随机推荐
- don't run elasticsearch as root.
因为安全问题elasticsearch 不让用root用户直接运行,所以要创建新用户 第一步:liunx创建新用户 adduser XXX 然后给创建的用户加密码 passwd XXX ...
- 【算法专题】后缀自动机SAM
后缀自动机是用于识别子串的自动机. 学习推荐:陈立杰讲稿,本文记录重点部分和感性理解(论文语言比较严格). 刷题推荐:[后缀自动机初探],题目都来自BZOJ. [Right集合] 后缀自动机真正优于后 ...
- input新类型详解
http://www.webhek.com/post/html5-input-type.html
- Python基础入门(一)
1.在线教程 2.Python下载地址,安装步骤,就是next.next... 3.配置环境变量(win8) 电脑 --> 属性 --> 高级系统设置 --> 环境变量,找到系统变量 ...
- Velocity VelocityEngine 支持多种loader 乱码问题
最近升级团队的代码生成工具,此工具是velocity实现的. 之前习惯使用UTF-8编码,现在团队使用GBK. 所以遇到一种场景,模板文件使用UTF-8(习惯了所有任性),输出文件使用GBK(项目需要 ...
- 单调栈(G - Sliding Window POJ - 2823 )
题目链接:https://cn.vjudge.net/contest/276251#problem/G 题目大意:给你n和m,然后问你对于(m,n)这中间的每一个数,(i-m+1,i)这个区间的最小值 ...
- [转]std::set、自定义类型与比较函数
转自:http://www.189works.com/article-42025-1.html 怎样在set中放入自定义类型?这个问题通过谷歌就可以得到不少答案:1.定义一个函数对象并在定义set的时 ...
- 解决 Electron 包下载太慢问题
项目下新建 .npmrc 文件,加入如下配置: electron_mirror=https://npm.taobao.org/mirrors/electron/ 即使用淘宝的源,重新 npm inst ...
- 2016.5.21——Compare Version Numbers
Compare Version Numbers 本题收获: 1.字符串型数字转化为整型数字的方法:s[i] - '0',( 将字母转化为数字是[i]-'A' ) 2.srt.at(),substr ...
- mipi 调试经验【转】
转自:http://blog.csdn.net/g_salamander/article/details/9163455 版权声明:本文为博主原创文章,未经博主允许不得转载. 以下是最近几个月在调试 ...