Evgenii Legotckoi
Evgenii LegotckoiMarch 19, 2023, 2:09 a.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
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 7:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 3:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 5:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks