控制缓存视图的缓存键命名

时间:2012-01-28 21:31:20

标签: python django caching memcached

我正在我的Django项目中缓存视图。

@cache_page(60 * 15)
def view_to_cache

因为用户可以编辑内容,所以我想在用户进行编辑时删除特定的缓存。为此,我将在编辑功能结束时cache.delete(KEY)

问题是,我不确定如何获取要删除的相应键的值。

我运行了memcached_stats来获取密钥,而且它们都是随机的。知道我怎么知道要删除哪个键?以下是缓存的示例:

>>> from memcached_stats import MemcachedStats
>>> mem = MemcachedStats()
>>> mem.stats()
{'auth_cmds': '0', 'reclaimed': '0', 'pid': '67140', 'cas_hits': '0', 'uptime': '3075', 'delete_misses': '0', 'listen_disabled_num': '0', 'cas_misses': '0', 'decr_hits': '0', 'incr_hits': '0', 'version': '1.4.5', 'limit_maxbytes': '67108864', 'bytes_written': '13604', 'incr_misses': '0', 'accepting_conns': '1', 'rusage_system': '0.073969', 'total_items': '13', 'cmd_get': '26', 'curr_connections': '12', 'threads': '4', 'total_connections': '33', 'cmd_set': '13', 'curr_items': '9', 'conn_yields': '0', 'get_misses': '7', 'bytes_read': '24226', 'cas_badval': '0', 'cmd_flush': '0', 'evictions': '0', 'bytes': '19492', 'connection_structures': '14', 'auth_errors': '0', 'rusage_user': '0.063413', 'time': '1327784334', 'delete_hits': '1', 'pointer_size': '64', 'decr_misses': '0', 'get_hits': '19'}
>>> mem.keys()
[':1:django.contrib.sessions.cachec7a594602214b4992c53575b3eda010d', ':1:views.decorators.cache.cache_header..511894add8326666c1a436bdb37e50ce.en-us', ':1:views.decorators.cache.cache_header..642ae686efc6dbc27b334fc0e1d22641.en-us', ':1:views.decorators.cache.cache_header..7739f0feb4375839a76f5cae2d10a69c.en-us', ':1:views.decorators.cache.cache_header..e32e41ea17bca494f9794fa87f5ec0d6.en-us', ':1:views.decorators.cache.cache_page..GET.511894add8326666c1a436bdb37e50ce.d41d8cd98f00b204e9800998ecf8427e.en-us', ':1:views.decorators.cache.cache_page..GET.642ae686efc6dbc27b334fc0e1d22641.d41d8cd98f00b204e9800998ecf8427e.en-us', ':1:views.decorators.cache.cache_page..GET.7739f0feb4375839a76f5cae2d10a69c.d41d8cd98f00b204e9800998ecf8427e.en-us', ':1:views.decorators.cache.cache_page..GET.e32e41ea17bca494f9794fa87f5ec0d6.d41d8cd98f00b204e9800998ecf8427e.en-us']
>>> cache.has_key(':1:django.contrib.sessions.cachec7a594602214b4992c53575b3eda010d')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'cache' is not defined
>>> from django.core.cache import cache
>>> cache.has_key(':1:django.contrib.sessions.cachec7a594602214b4992c53575b3eda010d')
False
>>> cache.has_key('1:django.contrib.sessions.cachec7a594602214b4992c53575b3eda010d')
False
>>> cache.has_key('django.contrib.sessions.cachec7a594602214b4992c53575b3eda010d')
True
>>> cache.has_key('views.decorators.cache.cache_page..GET.e32e41ea17bca494f9794fa87f5ec0d6.d41d8cd98f00b204e9800998ecf8427e.en-us')

1 个答案:

答案 0 :(得分:1)

它们不是随机的,它们是URL的md5哈希值。 get_cache_key中有django.utils.cache可以使用或查看重新创建密钥。它接受请求对象,我认为它使用request.pathsettings.LANGUAGE_CODE