1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was actually thinking of going through the celery route as I'm already using celery for my mail sending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.