[。。。]不知道是事故还是故事的东西

是这样的,今天把我的活干完,看到一段代码

然后,我发现了这样一段代码

@cache.cached(timeout=60, key_prefix='binary')
def random_binary():
    return random.sample(range(10 ** 5, 10 ** 6), 1)[0]

当时第一感觉是,为了这个东西要计算两次乘方?这个开销不必要的吧

但是还是觉得不对劲。。。仔细看了看

range(10 ** 5, 10 ** 6)

??????为了这个随机数,要生成长度九万的数组?几百k的内存???

但是,还有什么呢。。。

继续。。

生成的是随机数,然后用flask-cache缓存了??

但是用来缓存函数的不应该是flask-memoize吗?

但是随机数结果用来缓存了,还是随机数吗??

去flask-cache源码里面看一下

 1 class Cache(object):
 2     ......
 3         def memoize(self, timeout=None, make_name=None, unless=None):
 4         def memoize(f):
 5             @functools.wraps(f)
 6             def decorated_function(*args, **kwargs):
 7                 #: bypass cache
 8                 if callable(unless) and unless() is True:
 9                     return f(*args, **kwargs)
10 
11                 try:
12                     cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
13                     rv = self.cache.get(cache_key)
14                 except Exception:
15                     if current_app.debug:
16                         raise
17                     logger.exception("Exception possibly due to cache backend.")
18                     return f(*args, **kwargs)
19 
20                 if rv is None:
21                     rv = f(*args, **kwargs)
22                     try:
23                         self.cache.set(cache_key, rv,
24                                    timeout=decorated_function.cache_timeout)
25                     except Exception:
26                         if current_app.debug:
27                             raise
28                         logger.exception("Exception possibly due to cache backend.")
29                 return rv
30 
31             decorated_function.uncached = f
32             decorated_function.cache_timeout = timeout
33             decorated_function.make_cache_key = self._memoize_make_cache_key(
34                                                 make_name, decorated_function)
35             decorated_function.delete_memoized = lambda: self.delete_memoized(f)
36 
37             return decorated_function
38         return memoize

cache.memoize()是利用make_cache_key(f, *args, **kwargs)作为键存入redis的,那么make_cache_key是怎么工作的?

 1             def make_cache_key(*args, **kwargs):
 2                 if callable(key_prefix):
 3                     cache_key = key_prefix()
 4                 elif '%s' in key_prefix:
 5                     cache_key = key_prefix % request.path
 6                 else:
 7                     cache_key = key_prefix
 8 
 9                 return cache_key

结果就是,不管有多少请求,只要在60秒内,返回的结果都是一样的,随机的意义在哪呢。。。唯一的好处就是不会几百k的内存消耗变成几十M吧,画面太美

参考资料:

https://github.com/thadeusb/flask-cache/blob/master/flask_cache/__init__.py#L337

原文地址:https://www.cnblogs.com/fcyworld/p/7358585.html