In this article, you’ll get a comprehensive understanding of caching in Django and web development as a whole. You’ll learn about what caching is, the benefits of caching, how to set up caching in Django, the backend systems that Django supports, and the best practices of caching. By the end of the article, as a backend web developer, you’ll have a solid understanding of caching and how you can implement it in your Django projects for the best performance.
The Django framework is one of the most popular backend frameworks used by web developers these days. As a developer, building web applications with high performance should be one of the goals on your list. So building a web application in Django for high performance shouldn’t be a hassle, since Django comes with a caching framework that allows you to use various caching backends like in-memory cache, file-based cache, database cache, and more.
Table of Contents
Introduction to Django Caching
Caching in web development is a technique used by web developers to improve the performance of web applications. Every web application possesses resources that its users consistently desire to utilize. A resource could be anything from a straightforward web page to data stored in a database. Caching plays a significant role in maximizing the speed at which resources are accessed.
Common caching scenarios and use cases
The Django caching framework provides a wide range of scenarios and use cases that enable a developer to cache frequently accessed data. The following are the common caching scenarios:
Page Caching. This is a scenario where frequently visited pages on a site are entirely cached. The application fetches the cached versions of the pages and renders them when a request is made, as opposed to creating the content of the page from scratch.
Database Query Caching. Database query caching is a good approach for applications that depend on frequently requesting the database for information. A series of requests can be satisfied by the same piece of cached data without the need to hit the database, hence lowering database hits and speeding up server response time.
Session and Authentication Caching. Caching may be used to offer a streamlined user experience and a quicker response time. Since cached data will enable users to move easily across the authenticated sections of an application, caching authentication and session details can help to reduce redundant authentication operations.
Benefits of Django caching
Caching has grown more advantageous to web developers in this modern environment where data is of the essence and speed is more essential. These are some of the benefits of caching:
Improved Performance. Caching enhances the performance of web applications by reducing server load. When the server gets requests from the application, Caching ensures that some requests are satisfied using previously cached data. This prevents the server from having to conduct those operations from scratch. As a result, the users’ experience is improved overall, and reaction times are sped up.
Reduced response time. Caching minimizes response time by reducing database hits. Caching enables the data to be fetched from a convenient location rather than directly from the database each time it is needed. Since some data need pricey calculations that can take some time to complete, fetching data every time it is needed from the database might not be the best choice for all data. By saving the data and promptly making it available whenever needed, caching saves the day.
Resource Optimization. Caching data or resources in a web application, allows resources to be accessible and retrievable without performing repetitive operations that output the same resources.
Setting up A Django Project
The main tasks in this section are to create the virtual environment and install the required modules for the project. To create the virtual environment, enter this command in your terminal:
“`html
$ python -m venv project
“`
All the modules for the project will be installed inside this environment, so to start using it, we need to activate it. On Windows use this:
“`html
$ .\\project\\Scripts\\activate
“`
And on macOS or Linux, use this:
“`html
$ source project/bin/activate
“`
Before we implement caching, the first thing to do is set up a Django project. So let’s first install Django. Open your terminal, and run this command:
“`html
$ pip install django
“`
After successfully installing Django, let’s create a Django project and application. To create a Django project run:
“`html
$ django-admin startproject cachedproject
“`
Navigate into the project’s folder. Here, we’ll create a Django application. Run this command:
“`html
$ cd cachedproject
“`
And then run this:
“`html
$ python manage.py startapp cachedapplication
“`
After successfully creating the project and the application, we have to register the application to the project. Open the settings.py file, and make the INSTALLED_APPS list look like this:
“`html
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘cachedapplication’,
]
“`
Note: to use the application in your Django project, it must be registered in the INSTALLED_APPS list.
Now, to verify that the Django framework has been installed successfully, let’s test it. In the terminal, run this command:
“`html
$ python manage.py runserver
“`
Make sure you get the output pictured below. Now copy the URL and paste it into the web browser. The expected output is pictured below.
Note: you can read more about quickly starting a Django project and a Django app on SitePoint.
Configuring Different Caching Settings in settings.py
To use caching, we need to configure it in our Django project, so in this section, we’ll look at how we can configure different caching systems available in Django.
Local memory caching
As its name implies, Local Memory Cache, sometimes abbreviated as locmem, stores cached data in the RAM of the hosting machine. Django automatically uses local memory caching as the default caching system if you don’t provide an alternate caching mechanism in your settings.py file. Its thread-safe, quick, and responsive caching technique is notable. Local Memory Cache is less appropriate for use in production environments, since it includes a per-process mechanism that prevents any kind of cross-process caching and makes individual processes maintain separate private cache instances. It’s still a good choice, nevertheless, for development.
To configure local memory caching in your application, add the following code in the settings.py file:
“`html
CACHES = {
“default”: {
“BACKEND”: “django.core.cache.backends.locmem.LocMemCache”,
“LOCATION”: “unique-snowflake”,
}
}
“`
File-based caching
In file-based caching, each cache value is serialized and kept separately in a file when caching. It’s useful for small-scale applications or where memory-based caching is not practical. The downside of this caching system is that it’s relatively slower compared to memory-based caching.
To configure file-based caching in your application, add the following code in the settings.py file:
“`html
CACHES = {
“default”: {
“BACKEND”: “django.core.cache.backends.filebased.FileBasedCache”,
“LOCATION”: “/var/tmp/django_cache”,
}
}
“`
If you’re on Windows, make sure you start the location’s path with the respective drive letter like this:
“`html
CACHES = {
“default”: {
“BACKEND”: “django.core.cache.backends.filebased.FileBasedCache”,
“LOCATION”: “C:/my/path-to/file”,
}
}
“`
Database caching
Apart from storing caches in files and hosting the machine’s RAM, Django also provides the ability to store the cache in a database. This works best if you’ve got a fast, well-indexed database server.
To use database caching in your application, add the following code inside the settings.py:
“`html
CACHES = {
“default”: {
“BACKEND”: “django.core.cache.backends.db.DatabaseCache”,
“LOCATION”: “my_cache_table”,
}
}
“`
Use the following command to construct the database table mentioned in the setup above before using the cache:
“`html
python manage.py createcachetable
“`
The command above creates a table in the database in a proper format that Django’s database cache system expects. The name of the table is taken from the LOCATION. In this case, the table’s name will be my_cache_table.
Memcached caching
Memcached is an in-memory caching system that’s used by web developers even in several popular companies to reduce database access and increase site performance. In contrast to the locmem cache, Memcached operates as a daemon, which implies that the Memcached server runs as a background process, independently of any direct user interaction. Memcached must therefore be installed separately on your machine. Then in your Django application, install and configure one of its bindings, such as pylibmc or pymemcache, to use Memcached.
A Django application can be linked to a Memcached daemon by adding the cache settings, location, IP address, and other details, as shown below:
“`html
CACHES = {
“default”: {
“BACKEND”: “django.core.cache.backends.memcached.PyMemcacheCache”,
“LOCATION”: “127.0.0.1:11211”,
}
}
“`
Memcached technology is especially suited for applications with high read or query loads, as it was designed for fast retrieval of cached data.
Source link