比較的静的なデータセットに依存するトラフィックの多いビューのデータをキャッシュするために memcached を使用する Django のビューがあります。キーワードは相対的です。データベースで変更されたときに、その特定の URL のデータの memcached キーを無効にする必要があります。できるだけ明確にするために、ビューのミート アンド ポテトを次に示します (Person はモデル、キャッシュは 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 モデルの架空の save メソッドからのものです)。
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 のビューをどのように呼び出すでしょうか?