Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing specific cache in Django

I am using view caching for a django project.

It says the cache uses the URL as the key, so I'm wondering how to clear the cache of one of the keys if a user updates/deletes the object.

An example: A user posts a blog post to domain.com/post/1234/ .. If the user edits that, i'd like to delete the cached version of that URL by adding some kind of delete cache command at the end of the view that saves the edited post.

I'm using:

@cache_page(60 * 60)
def post_page(....):

If the post.id is 1234, it seems like this might work, but it's not:

def edit_post(....):
    # stuff that saves the edits
    cache.delete('/post/%s/' % post.id)
    return Http.....
like image 342
Brenden Avatar asked Jan 09 '12 05:01

Brenden


People also ask

How do I clear data cache in python?

After the use of the cache, cache_clear() can be used for clearing or invalidating the cache. These methods have limitations as they are individualized, and the cache_clear() function must be typed out for each and every LRU Cache utilizing the function.

Where is Django cache stored?

Django can store its cached data in your database. This works best if you've got a fast, well-indexed database server. To use a database table as your cache backend: Set BACKEND to django.

Does Django automatically cache?

Unless we explicitly specify another caching method in our settings file, Django defaults to local memory caching. As its name implies, this method stores cached data in RAM on the machine where Django is running. Local memory caching is fast, responsive, and thread-safe.


1 Answers

From django cache docs, it says that cache.delete('key') should be enough. So, it comes to my mind two problems you might have:

  1. Your imports are not correct, remember that you have to import cache from the django.core.cache module:

    from django.core.cache import cache
    
    # ...
    cache.delete('my_url')
    
  2. The key you're using is not correct (maybe it uses the full url, including "domain.com"). To check which is the exact url you can go into your shell:

    $ ./manage.py shell
    >>> from django.core.cache import cache
    >>> cache.has_key('/post/1234/')
    # this will return True or False, whether the key was found or not
    # if False, keep trying until you find the correct key ...
    >>> cache.has_key('domain.com/post/1234/') # including domain.com ?
    >>> cache.has_key('www.domain.com/post/1234/') # including www.domain.com ?
    >>> cache.has_key('/post/1234') # without the trailing / ?
    
like image 56
juliomalegria Avatar answered Oct 18 '22 10:10

juliomalegria