Reputation: 11335
I have this in my views.py
@cache_page(60 * 5)
def get_campaign_count(request):
return HttpResponse(
json.dumps({
'count': Campaign.objects.get_true_campaign_query().filter(dismissed=False).count()
},
cls=DjangoJSONEncoder
),
content_type='application/json')
Getting the count takes some time (20-40 seconds) each time it loads, so I decided to add caching to it with a 5 minute expiration time. My question is, is it possible to tell django to automatically re-cache the page during expiration? Otherwise another user would have to go through the 20-40 seconds wait before getting the response before other users benefit from the cache.
Upvotes: 1
Views: 609
Reputation: 111355
Nothing out of the box afaik. Your best bet would be probably running a background task (django manage command from crontab, or celery) every 5 min and manually caching that value under some key (with the expiration set to never expire), then reading it in the view by the key (no more whole page caching). I think this is the only way to keep 100% of requests cached and not return any stale data (older than 5 min).
If you don't mind showing the stale data to the first user after the 5 min have passed, then you can store a timestamp along with the value inside the cache to mark when this cache was last refreshed. This timestamp then can be used to manually check if 5 min have passed since the last refresh (this is to battle memcached standard behavior of returning nothing for expired values). If 5 min have passed, return the stale cached value to a user immediately and spawn a background thread to update the cached value.
Upvotes: 2