Python Module-61
Python Module-61
Prepared By,
Rini Kurian
Assistant Professor ,MCA
Web Frameworks : Introduction to Django, Projects and Apps
in Django, The Python Application Shell, The Django
Administration App, Creating an App using Django.
Django is a Python-based web framework that allows you to quickly createefficient web
applications. It is also called batteries included framework because
Django provides built-in features for everything including Django Admin Interface, default
database – SQLlite3, etc.
When you’re building a website, you always need a similar set of components: a way to handle
user authentication (signing up, signing in, signing out), a management panel for your website,
forms, a way to upload files, etc. Django gives you ready-made components to use and that too for
rapid development.
Why Django Framework ?
oUsed by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket,
Dropbox, etc. and the list is never-ending.
oThe last but not least reason to learn Django is Python, Python has huge library and features such
as Web Scrapping, Machine Learning, Image Processing, Scientific Computing, etc. One can
integrate it all this with web application and do lots and lots of advancestuff.
Advantages of Django
Here are few advantages of using Django which can be listed out here −
• Object-Relational Mapping (ORM) Support − Django provides a bridge between the data model and the
database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc.
Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases
supported are MongoDB and google app engine.
• Multilingual Support − Django supports multilingual websites through its built-in internationalization
system. So you can develop your website, which would support multiple languages.
• Framework Support − Django has built-in support for Ajax, RSS, Caching and various other frameworks.
• Administration GUI − Django provides a nice ready-to-use user interface for administrative activities.
• Development Environment − Django comes with a lightweight web server to facilitate end-to-end
application development and testing.
Features of Django
1. Excellent Documentation
If we compare Django with other open source technologies, it offers the best documentation in the market.
Better documentation of any technology is like a very well-established library for any developer. There, he
can search for any function desired with ease with the time involving in the searching purpose only.
The documentation of any technology is also one of the categories to grade a technology, as it lets other
developers other than its own creators to efficiently utilize the technology.
Django has been best at documentation from the beginning, from the point it became open source in 2005
to the present date, and the documentation has only been getting better with active development of
technology and it is also offered in different languages.
2. Python Web-framework
Python is also one of the main reasons people started learning Django. It is that one tool
which can solve all your problems and in any kind of operation out there, we can use it.
It’s very simple and easy to use. All these features are inside Python. In fact, Python is
currently the most popular language in the market.
If we have some basic knowledge of Python and web-working to start developing with
Django. It offers rapid development and it achieves so by being simple and logical.
3. SEO Optimised
This is a special feature of Django due to which it has edge over others.
SEO is Search Engine Optimization as from the name it means that adding your website to the search
engine such that it appears in the top results. As we know that the search engines do use some algorithms
which sometimes doesn’t cooperate much with the web-developer. Since we are creating our website in
the human understandable form and they have to add it in the URL form on the server so that its best
recognized by the search engine.
Django clears that concept by maintaining the website through URLs rather than the IP addresses on the
server, which makes it easy for SEO engineers to add the website to the server while the web-developer
don’t have to convert the URL into some numeric code.
4. High Scalability
A lot of MNCs on a worldwide scale uses Django and it gets implement there without any defects or errors.
It is the best example of Django being scalable.
Scalability means that at what scope or level, our technology gets to implement. For bigger websites like
Instagram, there are lots of active users (millions of them) which generate data in huge amounts (terabytes
of data/day). This kind of level requires our system or application to be very precise and error-free. It is, of
course, difficult even for programmers and web developers that have years of experience.
Django is written by those experienced programmers from scratch without using any python library
existing other then what the developers created themselves.
Thousands of tests and debugging and now with lots of time on the market side as the open source project
makes Django ideal for anyone who wants to make their websites error-free and scalable to a bigger
environment.
5. Versatile in Nature
Django is very versatile in its own Django way. The logical project structure and MVT architecture
of Django sometimes seem very limiting. But, that’s just opposite because by giving us the files it is
providing us with a solid foundation which can then be used to make whichever application we want
to create.
All that with integration with almost all the technologies out there with upgradations is by fulfilling
the industry standards.
It allows extending Django with all the technologies we work with and also with the upcoming ones.
Therefore, Django is the future of web development and everyone who was previously using PHP
will majorly use Django.
6. Offers High Security
Django is super secure. To prove the feature, you can always take examples of lots of websites
which are worldwide and posses huge traffic.
Django is secure because it covers the loopholes by default which were once left open for the
backend developer to complete. Although while using Django you may not feel it but those expert
backend developers can tell the quality and security of the work done by Django.
The writing of Django’s code is totally from scratch while that accounts for its other features as
well, but it also accounts for the security you are getting with this framework.
We cannot get the security at such a huge scale with this much expertise level of code in other
technologies.
It’s been written by web-developers keeping in mind what problems are faced by the same and
with that to get a rapid development speed.
7. Thoroughly Tested
Whenever we are learning a new technology, we want it to be durable and powerful enough to
withstand the dynamic changes happening in the industry.
Well, Django achieves that task with flying colors. We are trying to state that “Django has been in
the industry for more than a decade and is still a popular technology which is beating frameworks
like Laravel(PHP) in their own game.”
MNCs all over the world extensively uses Django for creating projects so we can say that it works
well to handle all the traffics and also accomplish international standards.
Its been around for so much time that lots of bugs and errors have been taken care of. It is a good
time to learn this technology.
The number of developers using Django for web development keeps growing day by day. Thus, it
makes Django a crowd-tested technology. If it was not stable or task accomplishing why would it gain
popularity and still be in the market.
8. Provides Rapid Development
Although, lots of technologies cover this feature as the primary feature but Django has so many other
better features that sets it apart.
Here, rapid development means that we won’t need expert backend knowledge to make a fully functional
website.
We will also not create separate server files to design the database and connect the same while also
making another file for transferring data to and from the server. Django handles this work and a lot of
other tasks. We won’t need extra files for each task.
These tasks are like half the project time and money, and they are surely important for almost any
website out there. While Django supports them inbuilt thus, allowing you to work more on your website’s
unique feature.
What does Django code look like?(Architecture)
•URLs: While it is possible to process requests from every single URL via a single function, it is much
more maintainable to write a separate view function to handle each resource. A URL mapper is used to
redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also
match particular patterns of strings or digits that appear in a URL and pass these to a view function as
data.
•View: A view is a request handler function, which receives HTTP requests and returns HTTP responses.
Views access the data needed to satisfy requests via models, and delegate the formatting of the
response to templates.
•Models: Models are Python objects that define the structure of an application's data, and
provide mechanisms to manage (add, modify, delete) and query records in the database.
•Templates: A template is a text file defining the structure or layout of a file (such as an HTML page),
with placeholders used to represent actual content. A view can dynamically create an HTML page using
an HTML template, populating it with data from a model. A template can be used to define the
structure of any type of file; it doesn't have to be HTML!
Installation of Django
To initiate a project of Django on Your PC, open Terminal and Enter the followingcommand
django-admin startproject projectName
A New Folder with name projectName will be created. To enter in the project using terminal enter
command
cd projectName
Now run,
Python manage.py runserver
Django is famous for its unique and fully managed app structure. For every functionality, an app
can be created like a completely independent module.
To create a basic app in your Django project you need to goto directory containing manage.py
and from there enter the command :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projectApp'
]
So, we have finally created an app but to render the app using urls we need to include the app in our
main project so that urls redirected to that app can be rendered.
Move to projectName-> projectName -> urls.py and addbelow code in the header
from django.urls import include
Now in the list of URL patterns, you need to specify app namefor including your app urls.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# Enter the app name in following syntax for this to work
path('', include("projectApp.urls")),
]
Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be
automatically included in your main project.
Create your views
def index(request):
return HttpResponse("<h1>Hello, world. </h1>")
def about(request):
return HttpResponse("<h2>about page</h2>")
Create urls.py in projectApp dir
urlpatterns=[
path('',views.index,name='index'),
path('about',views.about,name='about’)
Django Session
To set and get the Django session in views, one may use request.session. It is also possible
to set the session multiple times.
The session can also make the client-side stored Cookie data more secure. It can be used to abstract the
receiving and sending of cookies, use a session ID for identification, and store data in the database. The
session can also make use of the not accept cookies setting in the web browser.
Django Session Example
• A project represents the entire website whereas, an app is basically a submodule of the
project.
• A single project can contain multiple apps whereas, an app can also be used in different
projects.
• A project is like a blueprint of the entire web application whereas, apps are the building blocks
of an web application.
• We generally creates a single project for our website with one or more apps in it.
• A project maintains configuration and settings related to the whole web application. Apps on
the other hand, can be independent or related to one another.
The inheritance styles in Django
• Abstract base classes: This inheritance style is used by the developer when they want
parents class to retain the data which you do not want to type out for every single child
model.
• Proxy models: This inheritance style allows the user to modify the python level
behavior without actually modifying the model's field.
The Django Admin
• The administrative interface, or admin for short, allows trusted site administrators to
create, edit and publish content, manage site users, and perform other administrative
tasks.
• Django comes with a built-in admin interface. With Django’s admin you can
authenticate users, display and handle forms, and validate input; all automatically.
• Django admin—create a superuser login, register models with the admin, customize how
our models are viewed in the admin, add and edit model data, and understand how to
manage users in the admin
Accessing the Django Admin Site
To create an admin user, run the following command from inside your virtual environment:
First, make sure the development server is running, then open a web browser to
http://127.0.0.1:8000/admin/.
Django’s admin login screen.
This encapsulates n-dimensional arrays of homogeneous data types, with many operations being
performed in compiled code for performance.
NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically).
Changing the size of an ndarray will create a new array and delete the original.
The elements in a NumPy array are all required to be of the same data type, and thus will be the
same size in memory.
NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of
data. Typically, such operations are executed more efficiently and with less code than is possible
using Python’s built-in sequences.
traits
NumPy addresses the slowness problem partly by providing multidimensional arrays and functions
and operators that operate efficiently on arrays, requiring rewriting some code, mostly inner
Using NumPy in Python gives functionality comparable to MATLAB since they are both
interpreted, and they both allow the user to write fast programs as long as most operations work
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually
numbers), all of the same type, indexed by a tuple of positive integers.
For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one
axis.
That axis has a length of 3. In the example pictured below, the array has rank 2 (it is 2-dimensional).
The first dimension (axis) has a length of 2, the second dimension has a length of 3.
The more important attributes of an ndarray object are:
ndarray.ndim: The number of axes (dimensions) of the array. In the Python world, the number of dimensions
is referred to as rank.
ndarray.shape:The dimensions of the array. This is a tuple of integers indicating the size of the array in each
dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is
therefore the rank, or number of dimensions, ndim.
ndarray.size: The total number of elements of the array. This is equal to the product of the elements of
shape.
ndarray.dtype: An object describing the type of the elements in the array. One can create or specify dtype’s
using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and
numpy.float64 are some examples.
ndarray.itemsize: The size in bytes of each element of the array. For example, an array of elements of type
float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to
ndarray.dtype.itemsize.
ndarray.data: The buffer containing the actual elements of the array. Normally, we won’t need to use this
attribute because we will access the elements in an array using indexing facilities.
The ndarray data structure
The core functionality of numpy is its "ndarray", for n-dimensional array, data structure.
These arrays are strided views on memory.
In contrast to Python's built-in list data structure, these arrays are homogeneously typed:
all elements of a single array must be of the same type.
Array Creation
Create an array from a regular Python list or tuple using the array() function
import numpy as np
a = np.array([2,3,4])
b = np.array([1.2, 3.5, 5.1])
c = np.array([(1.5,2,3), (4,5,6)])
d = np.array( [ [1,2], [3,4] ], dtype=complex )
e=np.zeros( (3,4) )
f=np.ones( (2,3,4), dtype=np.int16 )
g=np.empty( (2,3) )
h=np.arange( 10, 30, 5 )
i=np.linspace( 0, 2, 9 )
Printing Arrays
When you print an array, NumPy displays it in a similar way to nested lists, but with the following
layout: the last axis is printed from left to right, the second-to-last is printed from top to bottom, the
rest are also printed from top to bottom, with each slice separated from the next by an empty line.
One-dimensional arrays are then printed as rows, bi dimensionals as matrices and tri dimensionals as
lists of matrices.
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the
result.
>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
Universal Functions
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal
functions”(ufunc).
Within NumPy, these functions operate elementwise on an array, producing an array as output.
>>> B = np.arange(3)
>>> B array([0, 1, 2])
>>> np.exp(B)
array([ 1. , 2.71828183, 7.3890561 ])
>>> np.sqrt(B)
array([ 0. , 1. , 1.41421356])
>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2., 0., 6.])
Limitations
Inserting or appending entries to an array is not as trivially possible as it is with Python's lists.
The np.pad(...) routine to extend arrays actually creates new arrays of the desired shape and padding values, copies
the given array into the new one and returns it.
NumPy's np.concatenate([a1,a2]) operation does not actually link the two arrays but returns a new one, filled with
the entries from both given arrays in sequence.
Reshaping the dimensionality of an array with np.reshape(...) is only possible as long as the number of elements in
the array does not change.
These circumstances originate from the fact that NumPy's arrays must be views on contiguous memory buffers. A
replacement package called Blaze attempts to overcome this limitation.
Examples
Array creation
Examples
Basic operations
Examples
Universal functions
Examples
Linear algebra
Examples
Nearest Neighbour Search - Iterative Python algorithm and vectorized NumPy version
INTRODUCTION
The scipy package contains various toolboxes dedicated to common issues in scientific computing. Its
different sub modules correspond to different applications, such as interpolation, integration,
optimization, image processing, statistics, special functions, etc.
• import scipy
scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU
Scientific Library for C and C++), or Matlab’s toolboxes.
scipy is the core package for scientific routines in Python; it is meant to operate efficiently on
numpy arrays, so that numpy and scipy work hand in hand.
Linear algebra operations: scipy.linalg
• scipy.misc.face(gray=False)
• Interpolation: scipy.interpolate
scipy.interpolate is useful for fitting a function from experimental data and thus evaluating points where
no measure exists.
The module scipy.stats contains statistical tools and probabilistic descriptions of random processes.
Random number generators for various randomprocess can be found in numpy.random.
• matplotlib is designed to be as usable as MATLAB, with the ability to use Python, with the
advantage that it is free.
• Both gnuplot and matplotlib are mature open-source projects. They both can produce many
types of different plots. While it is hard to specify a type of figure that one can do and the
other can not, they still have different advantages and disadvantages:
Comparison with GNUPLOT
Comparison with GNUPLOT
MATPLOTLIB
• It provides both a quick way to visualize data from Python and publication-quality figures in
many formats.
• To install matplotlib
• To use matplotlib
>>>import matplotlib
Python Matplotlib : Types of Plots
There are various plots which can be created using python matplotlib. Some of them are listed
below:
1.Line plot
2.Bar plot
3. Histogram
4. Scatter Plot
5. Area Plot
6. Pie Chart
Working With Multiple Plots
3D plot
from matplotlib import cm
Other Examples
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt image loading
import numpy as np import matplotlib.pyplot as plt
fig = plt.figure()
import scipy.misc
ax = fig.gca(projection='3d')
plt.gray()
X = np.arange(-5, 5, 0.25)
face = scipy.misc.face()
Y = np.arange(-5, 5, 0.25)
plt.imshow(face)
X, Y = np.meshgrid(X, Y)
plt.show()
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1,
cstride=1, cmap=cm.coolwarm)
plt.show()
Point of Difference Numpy Scipy
Performs basic operations such as sorting, indexing, etc. It is Used for complex operations such as algebraic
mostly used when working with data science and statistical functions, various numerical algorithms, etc.
Type of operations concepts.
Contains a variety of functions but these are not defined in Contains detailed versions of the functions like linear
depth. algebra that are completely featured.
Functions
NumPy Arrays are multi-dimensional arrays of objects which SciPy does not have any such array concepts as it is
are of the same type i.e. homogeneous. more functional. It has no constraints of homogeneity.
Arrays
Base Language of creation and NumPy is written in C and so has a faster computational SciPy is written in Python and so has a slower
speed speed. execution speed but vast functionality.