例如,像这样,是否有必要使用key_prefix
?
@cache.cached(timeout=50, key_prefix='all_comments')
def get_all_comments():
comments = do_serious_dbio()
return [x.author for x in comments]
cached_comments = get_all_comments()
在document中,它表示key_prefix
的默认值为request.path cache_key.:
,cache_key
的含义是什么,我该如何使用它? key_prefix
做了什么?
答案 0 :(得分:12)
首先,request.path
是script_root
之后的所有内容(除了参数)。例如:
对于http://127.0.0.1:5000/users/login/
这样的网址,请求数据为:
request.path is: /users/login/
对于上面链接示例中的网址http://www.example.com/myapplication/page.html?x=y
,请求数据为:
request.path is: /page.html
Q值。 cache_key是什么意思,我该如何使用它?
cache_key
是用于访问特定缓存值的键。如您所知,缓存是键值存储。
在Flask-Cache中,cache_key
由扩展程序生成,我们不应该自己使用它。
Q值。 key_prefix做了什么?
key_prefix
用于为缓存值生成cache_key
。请参阅make_cache_key
source,了解其完成情况。
Q值。是否有必要使用key_prefix?
假设您从2个不同的视图函数调用get_all_comments
,例如manage()
和view()
。在使用key_prefix
缓存get_all_comments
时,您不会指定@cached
。
第一次查看帖子到view
时get_all_comments
输出缓存为default key,如:view/view
或{{1 } {或view/module/view
的任何值,其中view/%s
是%s
。
接下来当您通过request.path
管理帖子时,不会从缓存中读取manage
输出,因为get_all_comments
已应用于从中获取数据缓存已更改为cache_key
且不是旧view/manage
,因为request.path现已更改。
这里缓存view/view
的重点是尽可能从缓存中获取数据,而不是db,但由于视图函数之间的键已经更改,因此数据实际上都是从db本身检索的。
但是,如果您指定了get_all_comments
key_prefix
,那么第一次从数据库中检索数据,下次all_comments
仍然是cache_key
找到值,并从缓存而不是db中访问数据。
因此,当您遇到上述情况时,使用all_comments
显然更好,在其他情况下,当总是从单个路径/视图函数调用该函数时,可以让默认值为使用
注意:为每个请求生成/计算cache_key,请参阅source:
key_prefix