我在Django中有一个视图,它使用memcached来缓存依赖于相对静态数据集的高流量视图的数据。关键词是相对的:当数据库中的数据发生变化时,我需要使特定URL数据的memcached密钥无效。为了尽可能清楚,这里的肉是一个'视图的土豆(人是模型,缓存是django.core.cache.cache):
def person_detail(request, slug):
if request.is_ajax():
cache_key = "%s_ABOUT_%s" % settings.SITE_PREFIX, slug
# Check the cache to see if we've already got this result made.
json_dict = cache.get(cache_key)
# Was it a cache hit?
if json_dict is None:
# That's a negative Ghost Rider
person = get_object_or_404(Person, display = True, slug = slug)
json_dict = {
'name' : person.name,
'bio' : person.bio_html,
'image' : person.image.extra_thumbnails['large'].absolute_url,
}
cache.set(cache_key)
# json_dict will now exist, whether it's from the cache or not
response = HttpResponse()
response['Content-Type'] = 'text/javascript'
response.write(simpljson.dumps(json_dict)) # Make sure it's all properly formatted for JS by using simplejson
return response
else:
# This is where the fully templated response is generated
我想要做的是以“未格式化”的形式获取cache_key变量,但我不知道该怎么做 - 如果可以完成的话。
万一已经有了这样的事情,这就是我想用它做的事情(这是来自Person模型的假设保存方法)
def save(self):
# If this is an update, the key will be cached, otherwise it won't, let's see if we can't find me
try:
old_self = Person.objects.get(pk=self.id)
cache_key = # Voodoo magic to get that variable
old_key = cache_key.format(settings.SITE_PREFIX, old_self.slug) # Generate the key currently cached
cache.delete(old_key) # Hit it with both barrels of rock salt
# Turns out this doesn't already exist, let's make that first request even faster by making this cache right now
except DoesNotExist:
# I haven't gotten to this yet.
super(Person, self).save()
我正在考虑为这种类型的东西创建一个视图类,并且在其中包含remove_cache
或generate_cache
中的函数,因为我这样做的东西是很多。这会是一个更好的主意吗?如果是这样,如果他们在一个类中,我将如何调用URLconf中的视图?
答案 0 :(得分:1)
URLConf应该指向任何可调用的。没有严格的要求让它完全指向功能。您可以使用缓存方法实现基类,然后扩展它:
class RealView(BaseViewWithCacheMethods):
def __call__(self, request):
if request.is_ajax():
return self.ajax_view()
return self.html_view()
URLConf的定义是这样的:
from django.conf.urls.defaults import *
from views import RealView
urlpattrens = patterns('',
(r'^$', RealView()),
)