我正在查询选举信息的数据库并在JSONP中将它们吐出来用于我们正在创建的一些ajax / jQuery小部件。
然而,我想要做的是缓存视图,以便每次呈现窗口小部件时都不会出现新请求。
我遇到了两个问题。
我应该使用哪种缓存方法来渲染此视图,以免数据库受到重创。
我需要将视图呈现为JSONP,这意味着我需要回调变量是动态的(当前我的脚本是我的脚本,但我担心它不适用于缓存视图)。
这是我的代码的样子。
from models import race
from models import candidates
from django.http import HttpResponse
from django.utils import simplejson
def data(request):
data = []
races = race.objects.all()
for election in races:
race_candidate = candidates.objects.filter(race__id=election.pk)
candidate_info = []
for n,candidate in enumerate(race_candidate):
candidate_values = {
"name":candidate.name,
"percent":candidate.percent,
"totalvotes":candidate.totalvotes,
"partyname":candidate.partyname,
"partyabbrv":candidate.partyabbrv,
}
candidate_info.append(candidate_values)
race_values = {
"title":election.title,
"description":election.description,
"priority":election.priority,
"decided":election.decided,
"candidates":candidate_info,
}
data.append(race_values)
json_races = '{"races":' + simplejson.dumps(data) + '}'
if("callback" in request.GET.keys()):
callback = request.GET["callback"]
else:
callback = None
if(callback):
response = HttpResponse("%s(%s)" % (
callback,
simplejson.dumps(data)
), mimetype="application/json"
)
else:
response = HttpResponse(json_races, mimetype="application/json")
return response
答案 0 :(得分:3)
您必须使用low-level cache API和您喜欢的缓存后端。
from django.core.cache import cache
...
CACHE_TIMEOUT = 3600 # choose your timeout
def data(request):
jsonstring = cache.get('elections')
if jsonstring is None:
data = [{
"title": election.title,
"description": election.description,
"priority": election.priority,
"decided": election.decided,
"candidates": [
{
"name": candidate.name,
"percent": candidate.percent,
"totalvotes": candidate.totalvotes,
"partyname": candidate.partyname,
"partyabbrv": candidate.partyabbrv,
} for candidate in election.candidates_set.all()
],
} for election in race.objects.all()]
jsonstring = simplejson.dumps(data)
cache.set('elections', jsonstring, CACHE_TIMEOUT)
callback = request.GET.get('callback')
if callback:
response = HttpResponse("%s(%s)" % (callback, jsonstring),
mimetype="application/json")
else:
response = HttpResponse('{"races":' + jsonstring + '}',
mimetype="application/json")
return response
在settings.py
中,根据documentation配置CACHE
。内存后端是最简单的,memcached可能是最好的。