How to create cache for dynamic posts displayed by page using Django

  • 2 days ago
Its easy to create a cache for a post using the Django Cache feature. The problem is when the posts are displayed in the search results or a history page. We need in some way to delete the dynamic pages because, otherwise the post's data will be updated individually, but on list for navigation or in the search results will be still old data.

This video shows a way how to delete a post from all pages where is displayed.

Gist url https://gist.github.com/InterTuts/2107198f0a131e553640e0d65fed9bbf
Transcript
00:00When I create a post in this app, the posts list here should be updated and the new created post should be displayed at the top.
00:17This posts list is stored first in the database, but to avoid multiple database requests, I'm storing the posts list in the cache after the first database request.
00:42It has infinite scrolling pagination.
00:51And for all individual pages in this list, I'm creating a cache key.
01:06Here are now three pages.
01:14Now, let's create a new post.
01:24As you can see, the new post isn't displayed in this list.
01:32This happens because here are displayed only the posts stored in the cache and I need to delete all posts after the post creation.
01:47The cache can be deleted only by using the key.
01:54Since I have now here three pages, I need to identify three cache keys and delete one by one the cache.
02:11Now, I will show how I'm deleting all cache keys for one user.
02:24I'm using this class to request the posts from the database and create the cache if it missing.
02:45Here I'm creating the cache.
02:48If the cache exists, I will return a response with the data from the cache and this code won't be executed.
03:06Here I have the cache manager file and the class.
03:15For each instance, I'm using the user ID to store the cache in two ways.
03:29Once, I'm storing the cache for the page number here and then I'm storing the cache keys in one key by using the user ID as a key for that cache
03:53because when I will clear the cache, I will use the user ID to list all saved keys here for pages and delete them.
04:16In this way, I will delete the user saved cache keys for all pages.
04:31Here is the class for post creation.
04:36When the post is created, I have to delete all saved pages in the cache for the user.
04:52In this way, all new posts will be displayed when I will create a new post.
05:00Now, let's create a new post.
05:05As you can see, the post list was updated and the new created post is displayed.

Recommended