Matt Andrews
Matt Andrews

Reputation: 2878

Advice needed on Django caching strategy

I'm deploying my first major Django app and am in need of some caching advice.

My site uses Google's Analytics API to show lists of "popular content" from around the site. These API calls are slow (2-5 seconds) so I cache their result for an hour. I then have a cron job which runs every 15 minutes and re-requests the data from Google. I realise this might seem a bit odd to cache it for an hour and update it every 15 minutes, I guess it's a kind of dumb failsafe.

I cache the main output of my site for several hours (it doesn't update much more frequently than that). This, of course, means that the part of the template which renders the "popular content" won't update in that time period, no matter how often I call the API.

I looked into Django's {% cache %} template tag and tried wrapping my "popular content" template view inside a minimally-cached wrapper (1 second cache time, for testing). This works (if I then manually call the Google API and reload my page, the template changes), but I'm not sure if it's going to work as I intend: basically, I don't want to cache the entire page for a few seconds (rather a few hours), but I want it to update when I fetch new data from Google.

Can anyone give me a nudge in the right direction here?

Upvotes: 0

Views: 212

Answers (1)

shanyu
shanyu

Reputation: 9716

If I get your question correctly, your async job must invalidate the relevant cache key when new data is fetched.

In your template you have this:

{% cache 6000 some-page-identifier %}

In your async task you invalidate data like this:

def fetch_data():
    # Fetch data first
    # Then invalidate the cached item
    cache.delete('some-page-identifier')

Upvotes: 1

Related Questions