Django中的Save()上的Memcached键无效
-
02-10-2019 - |
题
我在Django中有一个视图,该视图使用备忘录来缓存数据,以获取依赖相对静态数据的更高度运输的视图。关键词是相对的:我需要在数据库中更改该特定URL数据的模因密钥无效。为了尽可能清楚,这是肉类的肉(人是模型,缓存是django.core.cache.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变量,但我不确定该怎么做 - 如果可以做到这一点。
以防万一已经有事要这样做,这是我想处理的事情(这是来自人模型的假设保存方法)
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中的视图?
解决方案
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()),
)
不隶属于 StackOverflow