
Quick Contact
Python Tutorial
- What is Python?
- How to Install Python?
- Python Variables and Operators
- Python Loops
- Python Functions
- Python Files
- Python Errors and Exceptions
- Python Packages
- Python Classes and Objects
- Python Strings
- PostgreSQL Data Types
- Python Generators and Decorators
- Python Dictionary
- Python Date and Time
- Python List and Tuples
- Python Multithreading and Synchronization
- Python Modules
- What is Python bytecode?
- Python Regular Expressions
Python Panda Tutorial
- Python Pandas Tutorial
- Python Pandas Features
- Advantages and Disadvantages of Python Pandas
- Pandas Library In Python
- Pandas Series To Frame
- Python Dataframeaggregate and Assign
- Pandas Dataframe Describe
- Pandas Dataframe Mean
- Pandas Hist
- Pandas Dataframe Sum
- How to convert Pandas DataFrame to Numpy array
Python Selenium
- Selenium Basics
- Selenium with Python Introduction and Installation
- Navigating links using get method Selenium Python
- Locating Single Elements in Selenium Python
- Locating Multiple elements in Selenium Python
Python Flask Tutorial
Python Django
- How to Install Django and Set Up a Virtual Environment in 6 Steps
- Django MTV Architecture
- Django Models
- Django Views
- Django Templates
- Django Template Language
- Django Project Layout
- Django Admin Interface
- Django Database
- Django URLs and URLConf
- Django Redirects
- Django Cookies and Cookies Handling
- Django Caching
- Types of Caching in Django
- Django Sessions
- Django Forms Handling & Validation
- Django Exceptions & Error-handling
- Django Forms Validation
- Django Redirects
- Django Admin Interface
- Django Bootstrap
- Ajax in Django
- Django Migrations and Database Connectivity
- Django Web Hosting and IDE
- Django Admin Customization
- What is CRUD?
- Django ORM
- Django Request-Response Cycle
- Django ORM
- Making a basic_api with DRF
- Django Logging
- Django Applications
- Difference between Flask vs Django
- Difference between Django vs PHP
Numpy
- Numpy Introduction
- NumPy– Environment Setup
- NumPy - Data Types
- NumPy–Functions
- NumPy Histogram
- numPy.where
- numpy.sort
- NumPyfloor
- Matrix in NumPy
- NumPy Arrays
- NumPy Array Functions
- Matrix Multiplication in NumPy
- NumPy Matrix Transpose
- NumPy Array Append
- NumPy empty array
- NumPy Linear Algebra
- numpy.diff()
- numpy.unique()
- numpy.dot()
- numpy.mean()
- Numpy.argsort()
- numpy.pad()
- NumPyvstack
- NumPy sum
- NumPy Normal Distribution
- NumPylogspace()
- NumPy correlation
- Why we learn and use Numpy?
Tensorflow
- Introduction To Tensorflow
- INTRODUCTION TO DEEP LEARNING
- EXPLAIN NEURAL NETWORK?
- CONVOLUTIONAL AND RECURRENT NEURAL NETWORK
- INTRODUCTION TO TENSORFLOW
- INSTALLATION OF TENSORFLOW
- TENSORBOARD VISUALIZATION
- Linear regression in tensorflow
- Word Embedding
- Difference between CNN And RNN
- Explain Keras
- Program elements in tensorflow
- Recurrent Neural Network
- Tensorflow Object Detection
- EXPLAIN MULTILAYER PERCEPTRON
- GRADIENT DESCENT OPTIMIZATION
Interview Questions & Answers
Types of Caching in Django
There are different options of caching in Django:
-
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', } }
-
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.
-
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.
-
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', } }
-
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.
-
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', } }
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:
Code:
#Ducatindia #Dummy Caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } }
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.
-
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.
-
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:
-
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',
-
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
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