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
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

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

  • Result:53points,
  • Rating points-4
АА

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

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 7: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, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
K
KeithfapOct. 13, 2024, 9:24 p.m.
добавить qlineseries в функции North Symbol by Bubnov Ltd https://seven-elephants.com/en/categories/penthouse/ Искеле – жемчужина острова! Все факторы говорят про большой инвестиционный потенциал данного района как для …
JW
Jhon WickOct. 2, 2024, 3:52 a.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 9:09 p.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 4:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks