Quick Contact

    Python Tutorial
    Python Panda Tutorial
    Python Selenium
    Python Flask Tutorial
    Python Django
    Numpy
    Tensorflow
    Interview Questions & Answers

    Types of Caching in Django

    There are different options of caching in Django:

    1. Database Caching

      Database Caching is also one of the viable options when there is a fast database server. This type of Caching is more common and is most easily applicable.

      We will add this code section to settings.py file. Remove that Memcached section or comment it out.

      Code:

      #Ducatindia #Database Cache
      CACHES = {
      'default':{
      'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
      'LOCATION': 'dataflair_cache',
      }
      }
      
    2. Now, before starting our server, we will need to specify Django where to store its data. There shall be a particular table for it.

      In your command line, enter

      python manage.py createcachetable

      Understand the Code:

      When we use caching in Django, we need to declare a new dictionary in settings.py, named as CACHES. The name is default in Django.

      It takes one key default, which corresponds to the default value of the caching engine. Caching engine handles the cache generated by the server.

      There are particular keys in it, like:

      • BACKEND

        This field specifies which caching engine to use. Django provides you with many options for caching systems. In this case, our caching system is Database Caching.

      • LOCATION

        This field specifies the location of Cache Space. Tells the server where or on which machine it will be storing cache. In this case, our cache table name will be dataflair_cache.

    3. File-System Caching

      Django has this option as well. We can cache our data on our file system or any directory on the server, rather than main memory or database. This option is the most cost-efficient of all as it requires no hardware upgrades at all. The previous caching setups required better hardware as a prerequisite.

      This caching is slowest of all Cache Spaces. The software does depend on what you want to use. There are lots of frameworks out there and most of them work fine with Django.

      The File-based Caching means storing caches as individual files. The engine we use for file-system will serialize files. That makes it a better way to manage files.

      Just add this Code Section to settings.py file. Remember to delete other CACHE lists.

      Code:

      #Ducatindia #File System Cache
      CACHES = {
      'default': {
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
      'LOCATION': 'D:Django_Projects/ducatindia/Cache',
      }
      }
      

      This code contains the information of BACKEND engine for caching. Also, specify the location of the directory where the cache is stored.

      Some Important Points:

      • The server (Apache) should have access to this directory.
      • The directory should exist before running this code.
      • LOCATION should contain the absolute directory path. Django searches from the root of your file-system.
    4. Local-Memory Caching

      Django has a default caching system in the form of local-memory caching. It is very powerful and robust. This system can handle multi-threaded processes and is efficient.

      It is best for those projects which cannot use Memcached framework. It provides responses at the same speed. To implement local-memory caching, add this CACHES Dictionary to your settings.py file.

      Code:

      #Ducatindia #Local Memory Cache
      CACHES = {
      'default': {
      'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
      'LOCATION': 'DucatIndia',
      }
      }
      
    5. Dummy Caching

      Django also provides you with dummy caching. This implementation allows you to develop a website in a production environment.

      Suppose your website is in a production environment. There are some sections of code which use caching and you may not be capable of implementing caching in your development environment.

      Then, dummy caching will provide you the solution. It actually doesn’t cache anything and makes your server to interpret that caching is implemented.

      This approach is really helpful for developers. They don’t need to write code for implementing caching again. Thus, providing error-free websites and faster development.

      Add this code to your settings.py file to implement Dummy Caching.

    6. Code:

      #Ducatindia #Dummy Caching
      CACHES = {
      'default': {
      'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
      }
      }
      
    7. Custom Cache System

      Django supports a wide variety of caching implementations. If you want something that isn’t natively supported by Django like making your own cache backend, then you might want this setting which is really helpful.

      You can refer to cache backend in Django, get information on which fields are there and create your own backend accordingly. This code might be helpful here.

      Code:

      #Ducatindia #Custom Caching Engine
      CACHES = {
      'default': {
      'BACKEND': 'path.to.backend',
      }
      }
      

    Some Important Arguments

    These are some important caching arguments. You may require them according to your project. They are general arguments and can be applied on different caching engines.

    You can also define your own arguments when using custom caching engines. These arguments are keys in CACHES dictionary. Let’s understand them.

    1. TIMEOUT

      This argument takes time in seconds. It is similar to expire time for cookies. You can also define the expire time of cache data.

      By default, its 5 minutes or 300 seconds.

    2. OPTIONS

      This key is set for a particular option concerning that particular backend engine. It will have values for that backend. There are different options for Memcached and Local Memory Cache.

      These options are valid for local memory, database, and file-system caching implementations. You can define different options in custom cache engines as this field gives superior control over your cache data.

      These are some general options:

    • MAX_ENTRIES

      This argument takes in the maximum number of cache items that can be stored. Here the developer defines a capacity for the database, when capacity is filled.

      The server will culminate the previous entries.

    • CULL_FREQUENCY

      This sets up the frequency of deletion of cookies when the maximum number of entries has reached. This argument will take integer parameters as well.

      For example –

      You have given 2 as a value of CULL_FREQUENCY. When the MAX_ENTRIES is reached, the entries will be cut in half, like Thanos Snap and half of the entries are deleted.

      Implementation of Options in Database

    • KEY_PREFIX

      When working on a production site with many servers, the KEY_PREFIX value saves you from difficult to find errors.

      The Key prefix adds this value to every cache_id. So, for a particular server, there are no cache value collisions, since our cache systems consider multiple servers as one.

      The system is very efficient when we have a scaling project, but has its own problems. Django takes care of it by providing this parameter.

    • VERSION

      Django lets you create Key Prefixes but the nice point is, it also lets your version them. If a caching key is updated, you need not create a new key. We increment the version of that particular entry which makes it easy to access previous data.

      These concepts make sense when you have multiple servers and heavy traffic. It can increase the data redundancy but makes cache handling easier.

    • KEY_FUNCTION

      The KEY_FUNCTION generates KEY for your cache entries and takes in 3 parameters; KEY_PREFIX, VERSION, and Key itself which is generated by backend engine.

    Implementing Caching in Django

    In previous sections, we completed the setup of our caching system. Now, to implement caching on the website, there are these 2 popular ways:

    1. Per-site Caching

      Suppose we want our whole website to be cached. The part of per-site caching comes there. Just by adding this your whole website will be cached.

      Open your settings.py file and add these middlewares. Edit your MIDDLEWARE list.

      Code:

      #Ducatindia #Caching Middleware
      'django.middleware.cache.UpdateCacheMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.cache.FetchFromCacheMiddleware',
      
    2. Per-View Caching

      Websites often have some static and dynamic pages. Only dynamic pages require processing, static pages are served directly. Then caching the whole website means wasting memory.

      For efficient use of space, developers often cache particular view functions. That saves us a lot of space and thus caching only the important parts of the website.

      Although for that you need to know about Django Decorators. It is a different topic altogether and we will be covering the same in our future tutorials.

      To cache particular views, we use:

      Django.views.decorators.cache.cache_page() method.

      Import this function in your views.py file to implement caching. Use it just above the view that you want to be cached.

      For example-

      Code:

      #Ducatindia #View Caching
      fromdjango.views.decorators.cache import cache_page
      cache_page(200)
      #definition of the view function
      
    3. Understanding the code:

      The cache_page() method takes in one argument, the expiration time of cache data. The value is in seconds and we have given 200 in the above example.

      We can use cache_page() from urls_config, since there we call only one view function at a time. This method is more professional and makes the code more readable. All the cached function can be placed in one list.

      To use above method, wrap your view function with cache_page() in the path().

    Code:

    fromdjango.views.decorators.cache import cache_page
    urlpatterns = [
    path('index/', cache_page(300)view_function, ),
    #
    ]
    

     

    Apply now for Advanced Python Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.