Memory Caching in Django
Caching is used to save the result of an expensive operation so that there is no need to perform the operation again if its result is needed in the future. The pseudocode given below demonstrates how caching is done:
given a URL, try to find the page in the cache
if page is found in cache:
return the cached page
else:
generate the page
save the generated page in a cache
return the generated page
Django has an inbuilt caching system that enables its users to store their dynamic pages. This will mean that they will not have to calculate them again if they need them. Django is good at this, because the user can cache the following:
- The output of specific view.
- A part of the template.
- The entire site.
For Django developers to use the cache, they first have to specify where the cache will be stored. There are numerous possibilities for this as the cache can be stored in memory, database or on file system. For this to be set, one has to edit the file “settings.py” for the project.
- How to set up Cache in Database :-
Add the following code to the file “settings.py” of the project:
CACHES = {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.db.DatabaseCache’,
‘LOCATION’: ‘table_name’,
}
}
For the setting to be completed, we have to create a cache table and give it the name “table_name”.
- How to Set Up the Cache in Memory :-
This is the most effective way to set up the cache. However, it is determined by the Python Binding Library that you are using for your memory cache. The implementation can be done as shown below:
CACHES = {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.memcached.MemcachedCache’,
‘LOCATION’: ‘127.0.0.1:12344’,
}
}
Or
CACHES = {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.memcached.MemcachedCache’,
‘LOCATION’: ‘unix:/tmp/memcached.sock’,
}
}
- How to Cache the Entire Site :-
This is the simplest way that caching can be done in Django. For this to be done, the option “MIDDLEWARE_CLASSES” has to be edited in the file “settings.py”. Consider the code given below, which shows what has to be added to the section:
MIDDLEWARE_CLASSES += (
‘django.middleware.cache.UpdateCacheMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.cache.FetchFromCacheMiddleware’,
)
Note that the above should be implemented in the given order as if not done that way, errors will occur.
The following also need to be set in the same file:
CACHE_MIDDLEWARE_ALIAS –cache alias to be used for the storage.
CACHE_MIDDLEWARE_SECONDS – number of seconds that each page should be
cached.
- Caching a View :-
For those who don’t need to cache an entire site, they can choose to cache parts of an entire site. This can be done through the use of a decorator named “cache_page”, which comes inbuilt in Django. Suppose we need to cache the result of the view “vwArticles”. This can be done as shown below:
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def vwArticles(request, year, month):
text = “Displaying the articles of : %s/%s”%(year, month)
return HttpResponse(text)
The view given above was map to the following:
upatterns = patterns(‘myapplication.views’,
url(r’^articles/(?P<month>\d{2})/(?P<year>\d{4})/’, ‘vwArticles’, name =
‘articles’),)
- Caching a Template Fragment :-
One can also decide to catch parts of a fragment. The “cache” tag can be used for this purpose. The template “hello.html” is as shown below:
{% extends “template.html” %}
{% block title %}Hello Page{% endblock %}
{% block content %}
Hello there!!!<p>Today is on{{day}}</p>
We are on
{% if day.day == 1 %}
the first day of the month.
{% elif day == 30 %}
the last day of the month.
{% else %}
I am not aware.
{%endif%}
<p>
{% for today in days_of_week %}
{{day}}
</p>
{% endfor %}
{% endblock %}
For us to cache the content block, the template will be as follows:
{% load cache %}
{% extends ” template.html” %}
{% block title %} Hello Page{% endblock %}
{% cache 500 content %}
{% block content %}
Hello there!!!<p>Today is on{{day}}</p>
We are on
{% if day.day == 1 %}
the first day of the month.
{% elif day == 30 %}
the last day of the month.
{% else %}
I am not aware.
{%endif%}
<p>
{% for today in days_of_week %}
{{today}}
</p>
{% endfor %}
{% endblock %}
{% endcache %}
- Conclusion :-
We have come to the conclusion of the guide. Django is a very useful framework of Python that lets us develop web applications in an easy and quick manner. Before beginning to use this framework for development of web apps, you have to ensure that you have installed Python itself, a database system and as well as having set up a server. From there, you can begin to develop your web apps using all the helpful information in this episode.
Thank you
👈Episode 15(D)
Share this Post
PRINT THIS POST
No comments:
Post a Comment
If you have any doubts. Please let me know.