从Django缓存中删除所有匹配的键 [英] Remove all matching keys from Django cache
问题描述
我需要遍历服务器的缓存,该缓存是一个 LocMemCache
对象,并删除缓存中以字符串'rl:'
开头的每个键.据我了解,django缓存API提供的唯一功能是获取,设置和删除.这是我正在尝试做的一个粗略示例:
I need to iterate through my server's cache, which is a LocMemCache
object, and remove every key in the cache that begins with the string 'rl:'
. From what I understand, the only functions that the caching API django provides are get, set, and delete. Here is a rough example of what I am trying to do:
def clear_ratelimit_cache():
if any('rl:' in s for s in cache.get(s)):
log.info(
'FOUND SOMETHING')
cache.delete(*something else here*)
但是,尝试执行此操作给了我一个 NameError
,指出未定义全局名称s'
.还必须注意,缓存不可迭代.有没有人以类似的方式使用缓存并提出建议?
Trying to do this, however, gives me a NameError
, stating that global name 's' is not defined
. Also it must be noted that the cache is not iterable. Has anyone worked with the cache in a similar manner, and has a suggestion?
推荐答案
一种选择是使用在您的配置中单独为此数据类型命名的缓存,然后调用其 clear()
方法.
One option would be to have a separate, named cache in your configuration just for this data type, and then call its clear()
method.
否则,Django LocMemCache
将项目存储在实例的 _cache
属性中的简单 dict
中.由于他们没有为此提供API,因此您可以直接直接删除以下项目:
Otherwise, Django LocMemCache
stores items in a simple dict
, in the instance's _cache
attribute. Since they don't give you an API for this, you can simply remove the items directly:
for key in cache._cache.keys():
if key.startswith('rl:'):
del cache._cache[key]
通常免责声明,这是一个实现细节,不适用于其他缓存类型.
Usual disclaimer, this is an implementation detail that won't work with other cache types.
这篇关于从Django缓存中删除所有匹配的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!