English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To cache some expensive computation results, so that you don't have to execute them again the next time you need them. Here is the pseudocode explaining how caching works -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 given a URL, try finding that page in the cache if the page is in the cache: return the cached page else: generate the page save the generated page in the cache (for next time) return the generated page
Django provides its own caching system, which allows you to save dynamic web pages to avoid recalculating them when needed. The advantage of Django's caching architecture is that it allows you to cache -
The output of a specific view Part of the template The entire website
To use high-speed caching in Django, the first thing to do is to set where the cache will be saved. The caching framework provides different possibilities - Cache can be stored in the database, about the file system, or directly in memory. It can be set up in the project's settings.py file.
Just add the following to the project's settings.py file-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_table_name', } }
For this work, and to complete the settings, we need to create a high-speed cache table 'my_table_name'. For this, the following needs to be done -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 python manage.py createcachetable
Set high-speed cache in the file system
Just add the following to the project's settings.py file-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '',/var/tmp/django_cache } }
Set caching in memory
-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '',127.0.0.1:11211, } }
or
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'unix:/tmp/memcached.sock', } }
Cache the entire website
The simplest way to use high-speed caching in Django is to cache the entire website. This can be done by editing the MIDDLEWARE_CLASSES option in the project's settings.py file. The following needs to be added to the option-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', )
Please note that the order here is very important, and the update should be done before obtaining the middleware.
Then, in the same file, it is also necessary to set -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 CACHE_MIDDLEWARE_ALIAS – The cache alias to use for storage. CACHE_MIDDLEWARE_SECONDS – The number of seconds each page should be cached.
Cache view
If you don't want to cache the entire website, you can cache specific views. This can be done by using the cache_page decorator that comes with Django. We want to cache the result of the view viewArticles-
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from django.views.decorators.cache import cache_page @cache_page(60 * 15) def viewArticles(request, year, month): text = "Displaying articles of: %s"/%s"%(year, month) return HttpResponse(text)
As you can see, cache_page is the number of seconds (parameter) you want the view result to be cached. In the above example, the result will be cached 15 minutes.
Note - As we saw earlier, the above view is mapped to -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 urlpatterns = patterns('myapp.views', url(r'^articles/(?P<month>\d{2)/(?P<year>\d{4)/', 'viewArticles', name = 'articles'),)
Since the URL uses parameters, each different call will be executed separately. For example, the request /myapp/articles/02/2007 will be cached separately. /myapp/articles/03/2008.
Caching a view can also be directly completed in the url.py file. Next, there is the same result as described above. As long as you edit myapp/url.py file and change the relevant mapping URL (above) -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 urlpatterns = patterns('myapp.views', url(r'^articles/(?P<month>\d{2)/(?P<year>\d{4)/, cache_page(60 * 15)(viewArticles), name = 'articles'),)
Of course, it no longer needs myapp/views.py.
Cache template fragments
Parts of the template can also be cached, which is done by using the 'cache' tag. Let's modify the 'hello.html' template. -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 {% extends "main_template.html" %} {% block title %}My Hello Page{% endblock %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of the month. {% elif today == 30 %} the last day of the month. {% else %} I don't know. {% endif %} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %}
The cache content block template will become -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 {% load cache %} {% extends "main_template.html" %} {% block title %}My Hello Page{% endblock %} {% cache 500 content %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of the month. {% elif today == 30 %} the last day of the month. {% else %} I don't know. {% endif %} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %} {% endcache %}
As you can see above, cache tags will need2A parameter - The block to be cached (seconds) and the name provided to the cache fragment.