清除Django中的特定缓存 [英] Clearing specific cache in Django
问题描述
我正在为Django项目使用视图缓存.
I am using view caching for a django project.
它说缓存使用URL作为密钥,因此我想知道如果用户更新/删除对象,如何清除其中一个密钥的缓存.
It says the cache uses the URL as the key, so I'm wondering how to clear the cache of one of the keys if a user updates/deletes the object.
一个例子:一个用户在domain.com/post/1234/
上发布一个博客文章.如果用户对此进行了编辑,我想通过在视图末尾添加某种删除缓存命令来删除该URL的缓存版本.保存已编辑的帖子.
An example: A user posts a blog post to domain.com/post/1234/
.. If the user edits that, i'd like to delete the cached version of that URL by adding some kind of delete cache command at the end of the view that saves the edited post.
我正在使用:
@cache_page(60 * 60)
def post_page(....):
如果post.id为1234,则似乎可行,但这不是:
If the post.id is 1234, it seems like this might work, but it's not:
def edit_post(....):
# stuff that saves the edits
cache.delete('/post/%s/' % post.id)
return Http.....
推荐答案
From django cache docs, it says that cache.delete('key')
should be enough. So, it comes to my mind two problems you might have:
-
您的导入不正确,请记住必须从
django.core.cache
模块导入cache
:
from django.core.cache import cache
# ...
cache.delete('my_url')
您使用的密钥不正确(也许它使用了完整的URL,包括"domain.com").要检查确切的URL,可以进入您的shell:
The key you're using is not correct (maybe it uses the full url, including "domain.com"). To check which is the exact url you can go into your shell:
$ ./manage.py shell
>>> from django.core.cache import cache
>>> cache.has_key('/post/1234/')
# this will return True or False, whether the key was found or not
# if False, keep trying until you find the correct key ...
>>> cache.has_key('domain.com/post/1234/') # including domain.com ?
>>> cache.has_key('www.domain.com/post/1234/') # including www.domain.com ?
>>> cache.has_key('/post/1234') # without the trailing / ?
这篇关于清除Django中的特定缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!