Evgenii Legotckoi
Evgenii LegotckoiMarch 18, 2023, 4:09 p.m.

Django - Lesson 060. Speeding up a website with caching templates

One of the ways to significantly speed up the speed of a Django site is to cache both individual parts of the site templates and cache the templates after they are compiled by the site. Therefore, we will study both of these ways to improve the speed of the site, in addition to the way we already know the correct optimization of queries to the Django database . You can still test the effectiveness of improvements using the django-silk battery, which is described in the article on improving database queries.

Now let's look at options for using caching.

Caching parts of templates

In cases where you have generated parts of the templates, such as the footer of the site (Footer) or sidebars (SideBar), then it is possible to use caching of these parts of the site. For example, I not only cached them, but even the site's Navigation Drawer and top navigation bar. This was done because I use url embeddable tags and trans translation tags to generate navigation links, which are a lot of types, and together they add a decent load to the site. Not to mention that I use dynamically configurable widgets (you can read about this in the article on the polymorphic system of dynamic widgets . And it is these widgets that each load can double or even triple the time it takes to generate a site page, and given that the types of widgets can be very different, then it will not be possible to write a reasonably efficient database query.Therefore, it is easiest to code these parts of the site template.

It will look like this

{% load i18n cache %}
{% get_current_language as LANGUAGE_CODE %}
{% cache 6000 sidebar LANGUAGE_CODE %}
  {% load sidebar sidebar_sticky from evileg_widgets %}
  {% sidebar %}
  {% sidebar_sticky %}
{% endcache %}

This code uses the embeddable cache tag, which is passed the cache key sidebar , as well as the language code LANGUAGE_CODE as an additional parameter. Language code is required to support multilingual site.

In this case, with dynamic widgets, an important nuance arises, namely, cache invalidation if the SideBar with dynamic widgets was changed through the site's administrative panel.

So, it's implemented like this:

# -*- coding: utf-8 -*-

from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save, post_delete
from solo.models import SingletonModel
# Some another imports



class SideBar(SingletonModel):
    # Some code of model


class Widget(models.Model):
    # Some code of model


def invalidate_cache(**kwargs):
    for code, description in settings.LANGUAGES:
        cache.delete(make_template_fragment_key('sidebar', [code]))

post_save.connect(invalidate_cache, sender=SideBar)
post_save.connect(invalidate_cache, sender=Widget)
post_delete.connect(invalidate_cache, sender=Widget)

As you can see from the code, a system of signals is used here, which, by the way, is very similar to the [signals and slots in Qt] system (https://evileg.com/en/post/87/), which I really liked as a Qt developer.

So, this system of signals and slots invalidates the cache if both the SideBar object itself and in one of the widgets have been changed. Moreover, invalidation occurs immediately for all languages. Thus, heavy database queries occur no more than once every 6000 seconds. Which is perfectly acceptable.

Cached template loader

And the next way to improve site performance is to use a cached template loader. The fact is that Django usually looks for templates every time a site page is accessed, but if you set up caching on the template loader, then site performance can double.

For example, after enabling this option, the time for generating some pages of the site decreased from 220-240 ms to 120-130 ms. Of course, this is taking into account many other tweaks to improve performance. However, the result is very good.

And the setting of this functionality is done in the settigns.py file and it should look like this.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ os.path.join(BASE_DIR, 'templates') ],
        'OPTIONS': {
            # some another options
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ],
        },
    },
]

Conclusion

It is highly recommended to cache parts of the template, even if it's just calls to url or trans tags, in a global perspective, this can affect the quality of your site for search engines. It is not for nothing that there are so many articles on the Internet that say that search engines increase very fast sites in the search results.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 10:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 10:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 4:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks