Raydel Miranda
Raydel Miranda

Reputation: 14360

Update cache if content changes before cache TTL expires

I'm using redis for caching in a django app. I'm also using Django Rest Framework, and here is my problem.

I'm using the cache system like this:

from django.views.decorators.cache import cache_page

urlpatterns = [
...
    url(r'^some_url/$', cache_page(CACHE_TTL)(SomeView.as_view())
...
]

Here, SomeView is a class that inherits from APIView.

Now imagine we make a request to this url and we receive a json object containing one instance of whatever this url returns.

Then we proceed to delete (using django's admin interface) that object, and make the request again. The expected result is an empty json object, but what I'm receiving is the same object unchanged, the same happens if a new object is added, the response still only one object.

After some time (the TTL of the request in cache) the result is correct.

So, how can I tell django that a cache entry it is no valid any more?

Upvotes: 3

Views: 2107

Answers (1)

Raydel Miranda
Raydel Miranda

Reputation: 14360

From Django’s cache framework:

There are a few other ways to control cache parameters. For example, HTTP allows applications to do the following:

  • Define the maximum time a page should be cached.

  • Specify whether a cache should always check for newer versions, only delivering the cached content when there are no changes. (Some caches might deliver cached content even if the server page changed, simply because the cache copy isn’t yet expired.)

In Django, use the cache_control view decorator to specify these cache parameters. In this example, cache_control tells caches to revalidate the cache on every access and to store cached versions for, at most, 3,600 seconds:

from django.views.decorators.cache import cache_control

@cache_control(must_revalidate=True, max_age=3600)
def my_view(request):
    # ...

If the page you're caching varies frequently and you want to present those changes immediately (and you cache do not detect or check for changes automatically) without waiting for cache TTL, use cache_control.

Upvotes: 3

Related Questions