Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
76 views

Programming in Python

Uploaded by

Anushka Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Programming in Python

Uploaded by

Anushka Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

(Affiliated to Saurashtra University & Gujarat Technological University)

BCA – SEMESTER -6
SUB :- PYTHON

Edited BY :- Gaurav K Sardhara

PYTHON Page No :- 1 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

CS – 14 : PYTHON–BCA –SEM -6

Sr.No. Topic Detail

PYTHON Page No :- 2 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
1 Introduction to Python  A Brief History of Python,
and Python Syntax,  Strengths and Weaknesses,
Language Components /  Python Versions.
Collections & Functions  Installing Python,
 Environment Variables,
 Executing Python from the Command Line,
 IDLE,
 Editing Python Files,
 Getting Help,
 Dynamic Types,
 Python Reserved Words,
 Naming Conventions,
 Basic Syntax,
 Comments
 String Values,
 String Operations,
 The format Method,
 String Slices,
 String Operators,
 Numeric Data Types,
 Conversions,
 Simple Input and Output,
 The print Function.
 Control Flow and Syntax,
 Indenting,
 if_statement
 Relational Operators,
 Logical Operators, True or False,
 Bit Wise Operators.
 The while Loop, break and continue, The for
Loop,
 Lists, Tuples, Sets, Dictionaries, Sorting
Dictionaries,
 Copying Collections, Summary,
 Defining Your Own Functions, Parameters,
 Function Documentation,
 Keyword and Optional Parameters, Passing
Collections to a Function.

PYTHON Page No :- 3 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
2 Introduction to  HTTP Client-Server Request –
Web framework Response,
and DJango  concept of web framework and web
DJango Template application.
System  Introduction to Django, MVC Design
Pattern, Django_installation,
 setting up database,
 starting project.
 Django project architecture,
 Understanding manage.py,
 Understanding settings.py,
 Understanding __init__.py and wsgi.py,
 Understanding urls.py and Python regular
expression, Understanding admin.py,
 Understanding models.py,
 Understanding views.py ,
 Running Django development server
Template system basics,
 Using template system,
 basic template tags and filters,
 using templates in views, template loading.

3 Interaction with  Configuring database,


Database  defining model,
 basic data access,
 inserting and updating data, selecting
objects, deleting objects.
 clock, difftime, mktime, time, asctime, ctime,
gmtime, localtime, strftime

PYTHON Page No :- 4 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
4 Django Admin Site &  Activating the Admin interface,
Forms, Views and  Creating super user for Admin site,
URLConfs  Using the Admin site,
 Using Admin site, django.contrib package.
 Form basics, GET and POST methods ,
 Form validation,
 Rendering forms , ModelForm,
 Understanding the view layer,
 Requesting a web page via URL,
 Rendering web page via view function,
 Render HTTPResponse to templates,
 Understanding context data and Python
dictionary type.

5 Session and Cookies &  Cookies: Getting and Setting Cookies.


Testing and Deploying  Session: Django’s session framework: enabling
web application sessions,
 using session in views, session outside views.
 Testing Django, Python’s unittest2 library,
 Deploying Django application on GitHub /
Amazon Web Service.

PYTHON Page No :- 5 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

CHAPTER-1
Introduction to Python and Python Syntax, Language
Components / Collections & Functions

 A Brief History of Python :

 Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
 Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
 Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL).
 Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
 Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the removal
of duplicate programming constructs and modules so that "There should be
one -- and preferably only one -- obvious way to do it." Python 3.5.1 is the
latest version of Python 3.
 Python's exception model also resembles Modula-3's, with the addition of
an else clause.
 In 1994 comp.lang.python, the primary discussion forum for Python, was
formed, marking a milestone in the growth of Python's userbase.
 Strengths and Weaknesses :
 Strengths :

1.Readability and simplicity. Python code is very easy to read and understand.
The semantics of Python is very intuitive and simple.

2. Simplicity: It is easy start going with Python and it is easier to understand code
written in Python.

3. Libraries: Python has huge collection of Libraries if you don't believe me have a
look at this repository:
Python Extension Packages for Windows.
Also it is very easy to use libraries in Python, just install and import.
PYTHON Page No :- 6 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

4. User Community: It has a huge and supportive user community, that may be a
reason why it has huge collection of libraries.

5.Seductive: After using python a lot, there is always a danger that a programmer
would never find similar joy in any other programming language (except may be
Ruby).

A python coder would be less inclined to pick up any other language, because
other languages might seem hard/painful to use or simply are not fun enough.
Python is seductive enough to always keep you in it's trap.

6.popularity: There are certain circles that prefer Python for one reason or
another. In the math community for example, there is quite a lot of existing code
that can be leveraged. Also, Google has developed several open source projects in
Python. So if you want to use them, learning Python is a good idea.

 Weaknesses :
Disadvantages of Python are:- Python isn't the best for memory intensivetasks.
- Python is interpreted language & is slow compared to C/C++ or java.
- Python not a great choice for a high-graphic 3d game that takes up a lot of CPU.
- Python is evolving continuously, with constant evolution there is little
substantial documentation available for the language.

-Python is slow.
- Python is not a very good language for mobile development.
- Python is not a good choice for memory intensive tasks.
- It's near impossible to build a high-graphic 3D game using Python.
- Has limitations with database access.
- Python is not good for multi-processor/multi-core work.
1.Simple rules: Python is a very easy programming language. However, when one has
mastered it, one can be too accustomed to its features especially its late-binding
dynamic models and its extensive libraries.
2.Speed: python code is executed in n interpreter which makes slow execution of the
code.

 Versions of python :

Version 1 :-

 Python
 reached version 1.0 in January 1994. The major new features included in this
release were the functional programming tools lambda, map, filter and reduce.

PYTHON Page No :- 7 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Van Rossum stated that "Python acquired lambda, reduce(), filter() and map(),
courtesy of a Lisp hacker who missed them and submitted working patches".
 The last version released while Van Rossum was at CWI was Python 1.2. In
1995, Van Rossum continued his work on Python at the Corporation for
National Research Initiatives (CNRI) in Reston, Virginia whence he released
several versions.
 By version 1.4, Python had acquired several new features. Notable among
these are the Modula-3 inspired keyword arguments (which are also similar
to Common Lisp's keyword arguments) and built-in support for complex
numbers. Also included is a basic form of data hiding by name mangling,
though this is easily bypassed.

Version 2:-
 Python 2.0 introduced list comprehensions, a feature borrowed from
the functional programming languages SETL and Haskell. Python's syntax for
this construct is very similar to Haskell's, apart from Haskell's preference for
punctuation characters and Python's preference for alphabetic keywords.
Python 2.0 also introduced a garbage collection system capable of collecting
reference cycles.
 Python 2.1 was close to Python 1.6.1, as well as Python 2.0. Its license was
renamed Python Software Foundation License. All code, documentation and
specifications added, from the time of Python 2.1's alpha release on, is owned
by the Python Software Foundation (PSF), a non-profit organization formed in
2001, modeled after the Apache Software Foundation. The release included a
change to the language specification to support nested scopes, like
other statically scoped languages. (The feature was turned off by default, and
not required, until Python 2.2.)

Version 3:-
 Python 3.0 (also called "Python 3000" or "Py3K") was released on December 3,
2008. It was designed to rectify certain fundamental design flaws in the
language (the changes required could not be implemented while retaining full
backwards compatibility with the 2.x series, which necessitated a new major
version number). The guiding principle of Python 3 was: "reduce feature
duplication by removing old ways of doing things".

 Python 3.0 was developed with the same philosophy as in prior versions.
However, as Python had accumulated new and redundant ways to program the
same task, Python 3.0 had an emphasis on removing duplicative constructs and
modules, in keeping with "There should be one— and preferably only one —
obvious way to do it".

PYTHON Page No :- 8 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Version release dates
Release dates for the major and minor versions:

 Python 1.0 - January 1994


 Python 1.5 - December 31, 1997
 Python 1.6 - September 5, 2000
 Python 2.0 - October 16, 2000
 Python 2.1 - April 17, 2001
 Python 2.2 - December 21, 2001
 Python 2.3 - July 29, 2003
 Python 2.4 - November 30, 2004
 Python 2.5 - September 19, 2006
 Python 2.6 - October 1, 2008
 Python 2.7 - July 3, 2010
 Python 3.0 - December 3, 2008
 Python 3.1 - June 27, 2009
 Python 3.2 - February 20, 2011
 Python 3.3 - September 29, 2012
 Python 3.4 - March 16, 2014
 Python 3.5 - September 13, 2015
 Python 3.6 - December 23, 2016

 Installing python :

 Python distribution is available for a wide variety of platforms. You need to


download only the binary code applicable for your platform and install Python.
 If the binary code for your platform is not available, you need a C compiler to
compile the source code manually. Compiling the source code offers more
flexibility in terms of choice of features that you require in your installation.

 Here is a quick overview of installing Python on various platforms −

 Unix and Linux Installation :


Here are the simple steps to install Python on Unix/Linux machine.
 Open a Web browser and go to https://www.python.org/downloads/.
 Follow the link to download zipped source code available for Unix/Linux.
 Download and extract files.
 Editing the Modules/Setup file if you want to customize some options.
 run ./configure script
 make
 make install
This installs Python at standard location /usr/local/bin and its libraries
at/usr/local/lib/pythonXX where XX is the version of Python.

PYTHON Page No :- 9 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Windows Installation :
Here are the steps to install Python on Windows machine.
 Open a Web browser and go to https://www.python.org/downloads/.
 Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
 To use this installer python-XYZ.msi, the Windows system must support
Microsoft Installer 2.0. Save the installer file to your local machine and then
run it to find out if your machine supports MSI.
 Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.

 Python Environment Variables :

Here are important environment variables, which can be recognized by Python


S.No. Variable & Description


1 PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to
locate the module files imported into a program. It should include the Python
source library directory and the directories containing Python source code.
PYTHONPATH is sometimes preset by the Python installer.
2 PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is
executed every time you start the interpreter. It is named as .pythonrc.py in Unix
and it contains commands that load utilities or modify PYTHONPATH.
3 PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in
an import statement. Set this variable to any value to activate it.
4 PYTHONHOME
It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries
easy.

 Integrated Development Environment :


You can run Python from a Graphical User Interface (GUI) environment as well, if you
have a GUI application on your system that supports Python.
 Unix − IDLE is the very first Unix IDE for Python.
 Windows − PythonWin is the first Windows interface for Python and is an IDE
with a GUI.

PYTHON Page No :- 10 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Macintosh − The Macintosh version of Python along with the IDLE IDE is
available from the main website, downloadable as either MacBinary or
BinHex'd files.
If you are not able to set up the environment properly, then you can take help from
your system admin. Make sure the Python environment is properly set up and
working perfectly fine.
Note − All the examples given in subsequent chapters are executed with Python 2.4.3
version available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can
execute all the available examples online at the same time when you are learning
theory. Feel free to modify any example and execute it online.

 Executing Python from Command Line:

Running Python
There are three different ways to start Python −

Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Here is the list of all the available command line options −

S.No. Option & Description


1 -d
It provides debug output.

2 -O
It generates optimized bytecode (resulting in .pyo files).

3 -S
Do not run import site to look for Python paths on startup.

4 -v

PYTHON Page No :- 11 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
verbose output (detailed trace on import statements).

5 -X
disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6.

6 -c cmd
run Python script sent in as cmd string

7 File
run Python script from given file

Script from the Command-line


A Python script can be executed at command line by invoking the interpreter on your
application, as in the following −

$python script.py # Unix/Linux

or

python% script.py # Unix/Linux

or

C: >python script.py # Windows/DOS


Note − Be sure the file permission mode allows execution.

 IDLE:

IDLE (Integrated DeveLopment Environmentor Integrated Development


and Learning Environment) is an integrated development environment for Python,
which has been bundled with the default implementation of the language since
1.5.2b1. It is packaged as an optional part of the Python packaging with many Linux
distributions. It is completely written in Python and the Tkinter GUI toolkit
(wrapper functions for Tcl/Tk).
IDLE is intended to be a simple IDE and suitable for beginners, especially in an
educational environment. To that end, it is cross-platform, and avoids feature clutter.
According to the included README, its main features are:

 Multi-window text editor with syntax highlighting, autocompletion, smart indent


and other.
 Python shell with syntax highlighting.
 Integrated debugger with stepping, persistent breakpoints, and call stack visibility.
PYTHON Page No :- 12 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
IDLE has been criticized for various usability issues, including losing focus, lack of
copying to clipboard feature, lack of line numbering options, and general user
interface design; it has been called a "disposable" IDE, because users frequently move
on to a more advanced IDE as they gain experience.
Author Guido van Rossum says IDLE stands for "Integrated DeveLopment
Environment", and since van Rossum named the language Python partly to honor
British comedy group Monty Python, the name IDLE was probably also chosen partly
to honor Eric Idle, one of Monty Python's founding members.

 Reserved Words :
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only.
And Exec not
Assert Finally or
Break For pass
Class From print
Continue Global raise
Def If return
Del Import try
Elif In while
Else Is with
Except Lambda yield

 Comments in Python :
A hash sign (#) that is not inside a string literal begins a comment. All characters after
the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

PYTHON Page No :- 13 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

The Python language has many similarities to Perl, C, and Java. However, there are
some definite differences between the languages.

 Basic Syntax :
 The Python language has many similarities to Perl, C, and Java.
However, there are some definite differences between the
languages.

First Python Program


 Let us execute the programs in different modes of programming.

Interactive Mode Programming


 Invoking the interpreter without passing a script file as a parameter
brings up the following prompt −

 $ python

 Python 3.3.2 (default, Dec 10 2013, 11:35:01)
 [GCC 4.6.3] on Linux
 Type "help", "copyright", "credits", or "license" for more information.
 >>>

 On Windows:

 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC
v.1600 32 bit (Intel)] on win32
 Type "copyright", "credits" or "license()" for more information.
 >>>

 Type the following text at the Python prompt and press Enter −

 >>> print ("Hello, Python!")

PYTHON Page No :- 14 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 If you are running the older version of Python (Python 2.x), use of
parenthesis as inprint function is optional. This produces the
following result −

 Hello, Python!

Script Mode Programming


 Invoking the interpreter with a script parameter begins execution of
the script and continues until the script is finished. When the script is
finished, the interpreter is no longer active.
 Let us write a simple Python program in a script. Python files have
the extension .py. Type the following source code in a test.py file −

 print ("Hello, Python!")

 We assume that you have the Python interpreter set


in PATH variable. Now, try to run this program as follows −
 On Linux

 $ python test.py

 This produces the following result −

 Hello, Python!
 On Windows

 C:\Python34>Python test.py

 This produces the following result −

 Hello, Python!
 Let us try another way to execute a Python script in Linux. Here is the
modified test.py file −

 #!/usr/bin/python3
 print ("Hello, Python!")

 We assume that you have Python interpreter available in the /usr/bin


directory. Now, try to run this program as follows −

 $ chmod +x test.py # This is to make file executable


 $./test.py

PYTHON Page No :- 15 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 This produces the following result −

 Hello, Python!

Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double
quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

 String Values :
Python does not support a character type; these are treated as strings of length one,
thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example −
#!/usr/bin/python3

var1 = 'Hello World!'


var2 = "Python Programming"

print ("var1[0]: ", var1[0])


print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string
altogether. For example −
#!/usr/bin/python3

var1 = 'Hello World!'

print ("Updated String :- ", var1[:6] + 'Python')


When the above code is executed, it produces the following result −
Updated String :- Hello Python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented
with backslash.

PYTHON Page No :- 16 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
An escape character gets interpreted; in a single quoted as well as double quoted
strings.
Backslash Hexadecimal Description
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range
0.9, a.f, or A.F

 String Special Operators :


Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give
HelloPython
* Repetition - Creates new strings, concatenating multiple a*2 will give -
copies of the same string HelloHello
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give
ell
in Membership - Returns true if a character exists in the given H in a will give 1
string
not in Membership - Returns true if a character does not exist in M not in a will
the given string give 1
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints
characters. The syntax for raw strings is exactly the same as \n and print
for normal strings with the exception of the raw string R'\n'prints \n
operator, the letter "r," which precedes the quotation
marks. The "r" can be lowercase (r) or uppercase (R) and
must be placed immediately preceding the first quote mark.

PYTHON Page No :- 17 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
% Format - Performs String formatting See at next
section

 String Slice :
 We can also call out a range of characters from the string. Say we would like to
just print the word Shark. We can do so by creating a slice, which is a sequence
of characters within an original string. With slices, we can call multiple
character values by creating a range of index numbers separated by a
colon [x:y]:

 print(ss[6:11])
 Output
 Shark
 When constructing a slice, as in [6:11], the first index number is where the slice
starts (inclusive), and the second index number is where the slice ends
(exclusive), which is why in our example above the range has to be the index
number that would occur just after the string ends.

 When slicing strings, we are creating a substring, which is essentially a string


that exists within another string. When we call ss[6:11], we are calling the
substring Shark that exists within the string Sammy Shark!.

 If we want to include either end of a string, we can omit one of the numbers in
the string[n:n] syntax. For example, if we want to print the first word of
string ss — “Sammy” — we can do so by typing:

 print(ss[:5])
 Output
 Sammy

Format Method :

The Pythonic Way: The string method "format"

The Python help function is not very helpful concerning the string format method. All
it says is this:

| format(...)
| S.format(*args, **kwargs) -> str
PYTHON Page No :- 18 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
 Let's dive into this topic a little bit deeper: The format method was added in
Python 2.6. The general form of this method looks like this:

template.format(p0, p1, ..., k0=v0, k1=v1, ...)


 The template (or format string) is a string which contains one or more format
codes (fields to be replaced) embedded in constant text. The "fields to be
replaced" are surrounded by curly braces {}.

 The curly braces and the "code" inside will be substituted with a formatted
value from one of the arguments, according to the rules which we will specify
soon. Anything else, which is not contained in curly braces will be literally
printed, i.e. without any changes.

 If a brace character has to be printed, it has to be escaped by doubling it: {{ and


}}.

There are two kinds of arguments for the .format() method. The list of
arguments starts with zero or more positional arguments (p0, p1, ...), it may be
followed by zero or more keyword arguments of the form name=value.

A positional parameter of the format method can be accessed by placing the


index of the parameter after the opening brace, e.g. {0} accesses the first
parameter, {1} the second one and so on.

 The index inside of the curly braces can be followed by a colon and a format
string, which is similar to the notation of the string modulo, which we had
discussed in the beginning of the chapter of our tutorial, e.g. {0:5d}

 If the positional parameters are used in the order in which they are written,
the positional argument specifiers inside of the braces can be omitted, so '{} {}
{}' corresponds to '{0} {1} {2}'. But they are needed, if you want to access them
in different orders: '{2} {1} {0}'.

PYTHON Page No :- 19 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

The following diagram with an example usage depicts how the string method
"format" works works for positional parameters:

Examples of positional parameters:

>>> "First argument: {0}, second one: {1}".format(47,11)


'First argument: 47, second one: 11'
>>> "Second argument: {1}, first one: {0}".format(47,11)
'Second argument: 11, first one: 47'
>>> "Second argument: {1:3d}, first one: {0:7.2f}".format(47.42,11)
'Second argument: 11, first one: 47.42'
>>> "First argument: {}, second one: {}".format(47,11)
'First argument: 47, second one: 11'
>>> # arguments can be used more than once:
...
>>> "various precisions: {0:6.2f} or {0:6.3f}".format(1.4148)
'various precisions: 1.41 or 1.415'
>>>

In the following example we demonstrate how keyword parameters can be used with
the format method:

>>> "Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058)


'Art: 453, Price: 59.06'
>>>

PYTHON Page No :- 20 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

It's possible to left or right justify data with the format method. To this end, we can
precede the formatting with a "<" (left justify) or ">" (right justify). We demonstrate
this with the following examples:

>>> "{0:<20s} {1:6.2f}".format('Spam & Eggs:', 6.99)


'Spam & Eggs: 6.99'
>>> "{0:>20s} {1:6.2f}".format('Spam & Eggs:', 6.99)
' Spam & Eggs: 6.99'

Option Meaning
'<' The field will be left-aligned within the available space. This is usually the
default for strings.
'>' The field will be right-aligned within the available space. This is the default
for numbers.
'0' If the width field is preceded by a zero ('0') character, sign-aware zero-
padding for numeric types will be enabled.
>>> x = 378
>>> print("The value is {:06d}".format(x))
The value is 000378
>>> x = -378
>>> print("The value is {:06d}".format(x))
The value is -00378
',' This option signals the use of a comma for a thousands separator.
>>> print("The value is {:,}".format(x))
The value is 78,962,324,245
>>> print("The value is {0:6,d}".format(x))
The value is 5,897,653,423
>>> x = 5897653423.89676
>>> print("The value is {0:12,.3f}".format(x))
The value is 5,897,653,423.897
'=' Forces the padding to be placed after the sign (if any) but before the digits.
This is used for printing fields in the form "+000000120". This alignment
option is only valid for numeric types.
'^' Forces the field to be centered within the available space.

PYTHON Page No :- 21 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Unless a minimum field width is defined, the field width will always be the same size
as the data to fill it, so that the alignment option has no meaning in this case.

Additionally, we can modify the formatting with the sign option, which is only valid for
number types:

Option Meaning
'+' indicates that a sign should be used for both positive as well as negative
numbers.
'-' indicates that a sign should be used only for negative numbers, which is the
default behavior.
space indicates that a leading space should be used on positive numbers, and a
minus sign on negative numbers.
 Input and Output :

 In principle, every computer program has to communicate with the


environment or the "outside world".
 To this purpose nearly every programming language has special I/O
functionalities, i.e. input/output. This ensures the interaction or
communication with other components e.g. a database or a user.
 Input often comes - as we have already seen - from the keyboard and the
corresponding Python command or better the corresponding Python function
for reading from the standard input is input().

We have also seen in previous examples of our tutorial that we can write into
the standard output by using print.
 In this chapter of our tutorial we want to have a detailed look at the print
function. As some might have skipped over it, we want to emphasize that we
wrote "print function" and not "print statement".
 Outputting a result can be done with print() as we’ve just seen. We could make
it a little more helpful if we write it like this: print(“The temperature is “, F,
“F”).
 This is all well and good, whenever we want to convert 50°C to F. But it’d be
much more useful if we could somehow tell it any value of C! We can do this
just by replacing the first line, C = 50, with: C = input(“Enter the Centigrade
temperature:”)

 It prints out “Enter the Centigrade temperature:” (without the quotes) and
waits for the user to type in something.

PYTHON Page No :- 22 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 But if we try to do arithmetic on C, Python will complain about ‘unsupported
operand type(s)’. This is because input() delivers the user’s input as a string of
characters – it doesn’t know that we want it as a number.

 So we feed that string into int() (for integer) or float() (for decimal-pointed
numbers). When it has that number it does the arithmetic, and prints out the
result.

 Numeric Data Type :


 Number data types store numeric values. Number objects are created when
you assign a value to them. For example −

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For
example −

del var
del var_a, var_b

Python supports four different numerical types −


 int (signed integers)
 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Examples
Here are some examples of numbers −

int Long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J

PYTHON Page No :- 23 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
0x69 -4721885298529L 70.2-E12 4.53e-7j
 Python allows you to use a lowercase l with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python
displays long integers with an uppercase L.
 A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary
unit.

 Data Type Conversion :

 Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.
 There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted
value.

Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a
string.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Number Type Conversion :

 Python converts numbers internally in an expression containing mixed types to a


common type for evaluation. But sometimes, you need to coerce a number
explicitly from one type to another to satisfy the requirements of an operator or
function parameter.

PYTHON Page No :- 24 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
 Type complex(x, y) to convert x and y to a complex number with real part x
and imaginary part y. x and y are numeric expressions

 Print Function :

 we can write into the standard output by using print. In this chapter of our
tutorial we want to have a detailed look at the print function.

 As some might have skipped over it, we want to emphasize that we wrote
"print function" and not "print statement". You can easily find out how crucial this
difference is, if you take an arbitrary Python program written in version 2.x and if
you try to let it run with a Python3 interpreter.

 In most cases you will receive error messages. One of the most frequently
occurring errors will be related to print, because most programs contain prints. We
can generate the most typical error in the interactive Python shell:

$ python3
Python 3.2.3 (default, Apr 10 2013, 05:03:36)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 42
File "", line 1
print 42
^
SyntaxError: invalid syntax
>>>
This is a familiar error message for most of us: We have forgotten the parentheses.
"print" is - as we have already mentioned - a function in version 3.x. Like any other
function print expects its arguments to be surrounded by parentheses. So parenthesis
are an easy remedy for this error:

>>> print(42)
42
>>>

PYTHON Page No :- 25 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
But this is not the only difference to the old print. The output behaviour has changed
as well:

print Function
The arguments of the print function are the following ones:

print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)


The print function can print an arbitrary number of values ("value1, value2, ..."), which
are separated by commas. These values are separated by blanks. In the following
example we can see two print calls. We are printing two values in both cases, i.e. a
string and a float number:

>>> print("a = ", a)


a = 3.564
>>> print("a = \n", a)
a=
3.564
>>>
We can learn from the second print of the example that a blank between two values,
i.e. "a = \textbackslash n" and "3.564", is always printed, even if the output is
continued in the following line. This is different to Python 2, as there will be no blank
printed, if a new line has been started. It's possible to redefine the seperator between
values by assigning an arbitrary string to the keyword parameter "sep", e.e. an empty
string or a smiley:

>>> print("a","b")
ab
>>> print("a","b",sep="")
ab
>>> print(192,168,178,42,sep=".")
192.168.178.42
>>> print("a","b",sep=":-)")
a:-)b
>>>
A print call is ended by a newline, as we can see in the following usage:

>>> for i in range(4):


... print(i)
...
0
1
2
3
>>>
PYTHON Page No :- 26 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
To change this behaviour, we can assign an arbitrary string to the keyword parameter
"end". This string will be used for ending the output of the values of a print call:

>>> for i in range(4):


... print(i, end=" ")
...
0 1 2 3 >>>
>>> for i in range(4):
... print(i, end=" :-) ")
...
0 :-) 1 :-) 2 :-) 3 :-) >>>
The output of the print function is send to the standard output stream (sys.stdout) by
default. By redefining the keyword parameter "file" we can send the output into a
different stream e.g. sys.stderr or a file:

>>> fh = open("data.txt","w")
>>> print("42 is the answer, but what is the question?", file=fh)
>>> fh.close()
>>>
We can see that we don't get any output in the interactive shell. The output is sent to
the file "data.txt". It's also possible to redirect the output to the standard error
channel this way:

>>> import sys


>>> # output into sys.stderr:
...
>>> print("Error: 42", file=sys.stderr)
Error: 42
 Indenting :
Lines and Indentation:
One of the first caveats programmers encounter when learning Python is the fact
that there are no braces to indicate blocks of code for class and function definitions
or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. Both blocks in this example are fine:

if True:
print "True"
else:
print "False"

However, the second block in this example will generate an error:


PYTHON Page No :- 27 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the
use of the line continuation character (\) to denote that the line should continue. For
example:

total = item_one + \
item_two + \
item_three

Statements contained w
ithin the [], {}, or () brackets do not need to use the line continuation character. For
example:

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes can be used to span the string across multiple lines. For example, all
the following are legal:

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

 Control Flow :

 It is very important to control the program execution because in real scenarios


the situations are full of conditions and if you want your program to mimic the
real world closer then you need to transform those real world situations into
your program .
 For this you need to control the execution of your program statements. This
article is all about controlling the program execution sequence. It is commonly

PYTHON Page No :- 28 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
known as control flow in programming terms. So let’s dive in the river of
program statements that is controlled by python control flow tools.
 As the article is focusing on control flow tools , it is must for us to understand
these terms before we use them. The first word is control that simply means
controlling.

 We don’t want the default behavior, we want different one. We are getting
the different behavior by controlling some aspects of the behavior.
 Now it comes to flow,Flow is just a way or sequence of program execution. By
default every statement of program is executed one by one in an order they
appear in a program code.
 When we combine the above two words we get control flow,That simply
means controlling the flow of program execution to get desire behavior or
result.
 Using control flow we are controlling the statement execution, Now program
will no longer be executing in sequence, the execution is controlled by control
tools.
 To understand it let’s take few examples, In a bank management program we
don’t want to allow the retrieve function to work if the money in an account is
zero. In that acase we need to skip the retrieve program code and that is
control flow.

 If Statement :
 Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
 Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome. You need to determine which action to take and which
statements to execute if outcome is TRUE or FALSE otherwise.
 The if statement contains a logical expression using which data is compared
and a decision is made based on the result of the comparison.

 Syntax :

PYTHON Page No :- 29 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 if expression:

statement(s)

 If the boolean expression evaluates to TRUE, then the block of statement(s)


inside the if statement is executed. If boolean expression evaluates to FALSE,
then the first set of code after the end of the if statement(s) is executed.

 Flow Diagram


 Example :

#!/usr/bin/python

var1 = 100
if var1:
print "1 - Got a true expression value"
print var1

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"

 When the above code is executed, it produces the following result −

PYTHON Page No :- 30 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 1 - Got a true expression value


 100
 Good bye!

 An else statement can be combined with an if statement. An else statement


contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
 The else statement is an optional statement and there could be at most only
one else statement following if .

 ElIf Statement :
 The elif statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
 Similar to the else, the elif statement is optional. However, unlike else, for
which there can be at most one statement, there can be an arbitrary number
of elif statements following an if.

 syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

 Core Python does not provide switch or case statements as in other languages,
but we can use if..elif...statements to simulate switch case as follows −

 Example
#!/usr/bin/python

var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var

PYTHON Page No :- 31 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

else:
print "4 - Got a false expression value"
print var

print "Good bye!"

 When the above code is executed, it produces the following result −

3 - Got a true expression value


100
Good bye!
 Looping Statements :
 In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. There may be a
situation when you need to execute a block of code several number of times.
 Programming languages provide various control structures that allow for more
complicated execution paths.
 A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement −
 Python programming language provides following types of loops to handle
looping requirements.

Loop Type Description


while loop Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing the
loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for or
do..while loop.
 While Loop :
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −

while expression:
statement(s)

PYTHON Page No :- 32 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.

Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

 For Loop :
It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterating_var. Next, the statements
block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.

Example
#!/usr/bin/python
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y

PYTHON Page No :- 33 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango

Good bye!
 Nested Loop :
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.

Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as
follows −

while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other
type of loop. For example a for loop can be inside a while loop or vice versa.

Example
The following program uses a nested for loop to find the prime numbers from 2 to
100 −

#!/usr/bin/python
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
PYTHON Page No :- 34 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

print "Good bye!"

 Operators :

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.

 Types of Operator :
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

 Relational Operators :
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


== If the values of two operands are equal, then the condition (a == b)
becomes true. is not
true.
!= If values of two operands are not equal, then condition becomes
true.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not
true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b)
right operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value of right (a <= b)
operand, then condition becomes true. is true.

 Logical Operator :
There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then

PYTHON Page No :- 35 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Operator Description Example
and Logical If both the operands are true then condition becomes true. (a and
AND b) is
true.
or Logical OR If any of the two operands are non-zero then condition (a or b)
becomes true. is true.
not Logical Used to reverse the logical state of its operand. Not(a
NOT and b) is
false.
 Bitwise Operators :

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists in both (a & b)
operands (means
0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61
(means
0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49
both. (means
0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61
Complement (means
1100 0011
in 2's
complement
form due to
a signed
binary
number.
<< Binary Left Shift The left operands value is moved left by the number a << = 240
PYTHON Page No :- 36 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
of bits specified by the right operand. (means
1111 0000)
>> Binary Right Shift The left operands value is moved right by the a >> = 15
number of bits specified by the right operand. (means
0000 1111)
 Break Statement :
 It terminates the current loop and resumes execution at the next statement,
just like the traditional break statement in C.
 The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.
 If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.

 Syntax
 The syntax for a break statement in Python is as follows −

 break

 Flow Diagram


 Example
 #!/usr/bin/python
 for letter in 'Python': # First Example
 if letter == 'h':

PYTHON Page No :- 37 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 break
 print 'Current Letter :', letter

 var = 10 # Second Example


 while var > 0:
 print 'Current variable value :', var
 var = var -1
 if var == 5:
 break
 print "Good bye!"

 When the above code is executed, it produces the following result −

 Current Letter : P
 Current Letter : y
 Current Letter : t
 Current variable value : 10
 Current variable value : 9
 Current variable value : 8
 Current variable value : 7
 Current variable value : 6
 Good bye!

 Continue Statement :
It returns the control to the beginning of the while loop.. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves
the control back to the top of the loop.
The continue statement can be used in both while and for loops.

Syntax
continue

PYTHON Page No :- 38 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Flow Diagram

Example
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
PYTHON Page No :- 39 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

Current variable value : 2


Current variable value : 1
Current variable value : 0
Good bye!

 Python Lists :
The list is a most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets. Important thing about
a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between
square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.

 Accessing Values in Lists :


To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
 Updating Lists :
You can update single or multiple elements of lists by giving the slice on the left-hand
side of the assignment operator, and you can add to elements in a list with the
append() method. For example −
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Note: append() method is discussed in subsequent section.
PYTHON Page No :- 40 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001
 Delete List Elements :
To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note: remove() method is discussed in subsequent section.

 Tuple :
 A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
 Creating a tuple is as simple as putting different comma-separated values.
Optionally you can put these comma-separated values between parentheses
also. For example −
 tup1 = ('physics', 'chemistry', 1997, 2000);
 tup2 = (1, 2, 3, 4, 5 );
 tup3 = "a", "b", "c", "d";
 The empty tuple is written as two parentheses containing nothing −
 tup1 = ();
 To write a tuple containing a single value you have to include a comma, even
though there is only one value −
 tup1 = (50,);
 Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.

PYTHON Page No :- 41 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Accessing Values in Tuples:
 To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example −
 #!/usr/bin/python

 tup1 = ('physics', 'chemistry', 1997, 2000);
 tup2 = (1, 2, 3, 4, 5, 6, 7 );

 print "tup1[0]: ", tup1[0]
 print "tup2[1:5]: ", tup2[1:5]
 When the above code is executed, it produces the following result −
 tup1[0]: physics
 tup2[1:5]: [2, 3, 4, 5]
 Updating Tuples :
 Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new
tuples as the following example demonstrates −
 #!/usr/bin/python

 tup1 = (12, 34.56);
 tup2 = ('abc', 'xyz');

 # Following action is not valid for tuples
 # tup1[0] = 100;

 # So let's create a new tuple as follows
 tup3 = tup1 + tup2;
 print tup3
 When the above code is executed, it produces the following result −
 (12, 34.56, 'abc', 'xyz')

 Delete Tuple Elements

 Removing individual tuple elements is not possible. There is, of course,


nothing wrong with putting together another tuple with the undesired
elements discarded.
 To explicitly remove an entire tuple, just use the del statement. For example:
 #!/usr/bin/python

PYTHON Page No :- 42 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 tup = ('physics', 'chemistry', 1997, 2000);



 print tup
 del tup;
 print "After deleting tup : "
 print tup

 Dictionary :
 Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
 Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type
such as strings, numbers, or tuples.

 Accessing Values in Dictionary:

 To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example −
 #!/usr/bin/python

 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

 print "dict['Name']: ", dict['Name']
 print "dict['Age']: ", dict['Age']
 When the above code is executed, it produces the following result −
 dict['Name']: Zara
 dict['Age']: 7
 If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows −
 #!/usr/bin/python

 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

 print "dict['Alice']: ", dict['Alice']
 When the above code is executed, it produces the following result −
 dict['Alice']:
 Traceback (most recent call last):
 File "test.py", line 4, in <module>
 print "dict['Alice']: ", dict['Alice'];
 KeyError: 'Alice'
PYTHON Page No :- 43 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
 Updating Dictionary :

 You can update a dictionary by adding a new entry or a key-value pair,


modifying an existing entry, or deleting an existing entry as shown below in
the simple example −
 #!/usr/bin/python

 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

 dict['Age'] = 8; # update existing entry
 dict['School'] = "DPS School"; # Add new entry


 print "dict['Age']: ", dict['Age']
 print "dict['School']: ", dict['School']
 When the above code is executed, it produces the following result −
 dict['Age']: 8
 dict['School']: DPS School

 Delete Dictionary Elements :

 You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.
 To explicitly remove an entire dictionary, just use the del statement. Following
is a simple example −
 #!/usr/bin/python

 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

 del dict['Name']; # remove entry with key 'Name'
 dict.clear(); # remove all entries in dict
 del dict ; # delete entire dictionary

 print "dict['Age']: ", dict['Age']
 print "dict['School']: ", dict['School']
 This produces the following result. Note that an exception is raised because
after del dict dictionary does not exist any more −
 dict['Age']:
 Traceback (most recent call last):
 File "test.py", line 8, in <module>
PYTHON Page No :- 44 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

 print "dict['Age']: ", dict['Age'];


 TypeError: 'type' object is unsubscriptable
 Note: del() method is discussed in subsequent section.

 Defining Function :

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.

 Defining a Function :
You can define functions to provide the required functionality. Here are simple rules
to define a function in Python.
 Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.

Syntax :
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in
the same order that they were defined.
Example :
The following function takes a string as input parameter and prints it on standard
screen.
def printme( str ):
"This prints a passed string into this function"
print str
return

PYTHON Page No :- 45 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Calling a Function :
 Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
 Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. Following is the
example to call printme() function −

#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function!
Again second call to the same function

 Passing Parameters to Function :

There is one more thing we will cover in this (monsterously huge) lesson - passing
parameters to a function. Thinkback to how we defined functions:

Code Example 12 - Defining functions with parameters

def function_name(parameter_1,parameter_2):
{this is the code in the function}
{more code}
{more code}
return {value (e.g. text or number) to return to the main program}

 Where parameter_1 and parameter_2 are (between the parentheses), you put
the names of variables that you want to put the parameters into.
 Put as many as you need, just have them seperated by commas. When you run
a function, the first value you put inside the parentheses would go into the
variable where parameter_1 is.
 The second one (after the first comma) would go to the variable where
parameter_2 is. This goes on for however many parameters there are in the
function (from zero, to the sky) For example:
PYTHON Page No :- 46 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
Code Example 13 - how parameters work

def funnyfunction(first_word,second_word,third_word):
print "The word created is: " + first_word + second_word + third_word
return first_word + second_word + third_word

 When you run the function above, you would type in something like this:
funnyfunction("meat","eater","man").
 The first value (that is, "meat") would be put into the variable called
first_word. The second value inside the brackets (that is, "eater") would be put
into the variable called second_word, and so on.
 This is how values are passed from the main program to functions - inside the
parentheses, after the function name.

PYTHON Page No :- 47 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

CHAPTER-2
Introduction to Web framework and DJango DJango
Template System
 HTTP Client-Server Request – Response :

 The Hypertext Transfer Protocol (HTTP) is an application-level protocol for


distributed, collaborative, hypermedia information systems. This is the
foundation for data communication for the World Wide Web (i.e. internet)
since 1990.
 HTTP is a generic and stateless protocol which can be used for other purposes
as well using extensions of its request methods, error codes, and headers.
 Basically, HTTP is a TCP/IP based communication protocol, that is used to
deliver data (HTML files, image files, query results, etc.) on the World Wide
Web. The default port is TCP 80, but other ports can be used as well.
 It provides a standardized way for computers to communicate with each
other. HTTP specification specifies how clients' request data will be
constructed and sent to the server, and how the servers respond to these
requests.

 Basic Architecture :
The following diagram shows a very basic architecture of a web application and
depicts where HTTP sits:

The HTTP protocol is a request/response protocol based on the client/server based


architecture where web browsers, robots and search engines, etc. act like HTTP
clients, and the Web server acts as a server.

PYTHON Page No :- 48 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Client :
The HTTP client sends a request to the server in the form of a request method, URI,
and protocol version, followed by a MIME-like message containing request modifiers,
client information, and possible body content over a TCP/IP connection.

 Server :
The HTTP server responds with a status line, including the message's protocol version
and a success or error code, followed by a MIME-like message containing server
information, entity meta information, and possible entity-body content.

 Web Framework :

 A web framework (WF) or web application framework (WAF) is a software


framework that is designed to support the development of web
applications including web services, web resources, and web APIs.

 Web frameworks, provide a standard way to build and deploy web


applications. Web frameworks aim to automate the overhead associated with
common activities performed in web development. For example, many web
frameworks
provide libraries for database access, templating frameworks,and session mana
gement, and they often promote code reuse.[1] Although they often target
development of dynamic web sites, they are also applicable to static websites.

Types of framework architectures


Most web frameworks are based on the model–view–controller (MVC) pattern.
 Model–view–controller (MVC)
Main article: Model–view–controller

Many frameworks follow the MVC architectural pattern to separate the data
model with business rules from the user interface. This is generally considered a good
practice as it modularizes code, promotes code reuse, and allows multiple interfaces
to be applied. In web applications, this permits different views to be presented, such
as web pages for humans, and web service interfaces for remote applications.
 Push-based vs. pull-based
Most MVC frameworks follow a push-based architecture also called "action-based".
These frameworks use actions that do the required processing, and then "push" the
data to the view layer to render the results. Django, Ruby on Rails, Symfony, Spring
MVC, Stripes, CodeIgniter are good examples of this architecture.

PYTHON Page No :- 49 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Three-tier organization
In three-tier organization, applications are structured around three physical tiers:
client, application, and database.The database is normally an RDBMS. The application
contains the business logic, running on a server and communicates with the client
using HTTP. The client on web applications is a web browser that runs HTML
generated by the application layer.

 Framework applications :
Frameworks are built to support the construction of internet applications based on a
single programming language, ranging in focus from general purpose tools such as
Zend Framework and Ruby on Rails, which augment the capabilities of a specific
language, to native-language programmable packages built around a specific user
application, such as Content Management systems, some mobile development tools
and some portal tools.
 General-purpose website frameworks :
Web frameworks must function according to the architectural rules of browsers and
web protocols such as HTTP, which is stateless. Webpages are served up by
a server and can then be modified by the browser using JavaScript. Either approach
has its advantages and disadvantages.
Server-side page changes typically require that the page be refreshed, but allow any
language to be used and more computing power to be utilized. Client-side changes
allow the page to be updated in small chunks which feels like a desktop application,
but are limited to JavaScript and run in the user's browser, which may have limited
computing power. Some mix of the two is typically used.[17] Applications which make
heavy use of JavaScript are called single-page applications and typically make use of a
client-side JavaScript web framework to organize the code.
Server-side

 Django
 Zend Framework

Client-side
Main article: Single-page application

Examples include Backbone.js, AngularJS, EmberJS, ReactJS and Vue.js.


 Web Application :

 In computing, a web application or web app is a client–server software


application in which the client (or user interface) runs in a web
browser. Common web applications include webmail, online retail

PYTHON Page No :- 50 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
sales, online auctions, wikis, instant messaging services and many other
functions.

 The general distinction between a dynamic web page of any kind and a "web
application" is unclear. Web sites most likely to be referred to as "web
applications" are those which have similar functionality to a desktop software
application, or to a mobile app. HTML5 introduced explicit language support
for making applications that are loaded as web pages, but can store data
locally and continue to function while offline.
 Single-page applications are more application-like because they reject the
more typical web paradigm of moving between distinct pages with different
URLs. Single-page frameworks like Sencha Touch and AngularJS might be used
to speed development of such a web app for a mobile platform.
 Mobile web applications
There are several ways of targeting mobile devices when making a web application:

 Responsive web design can be used to make a web application - whether a


conventional web site or a single-page application viewable on small screens and
work well with touchscreens.
 Progressive Web Apps are a hybrid of regular web pages (or websites) and a
mobile application.

 Structure :
 Applications are usually broken into logical chunks called "tiers", where every
tier is assigned a role.Traditional applications consist only of 1 tier, which
resides on the client machine, but web applications lend themselves to an n-
tiered approach by nature. Though many variations are possible, the most
common structure is the three-tiered application.
 In its most common form, the three tiers are
called presentation, application and storage, in this order. A web browser is
the first tier (presentation), an engine using some dynamic Web content
technology
(suchas ASP, CGI, ColdFusion, Dart, JSP/Java, Node.js, PHP, Python or Ruby on
Rails) is the middle tier (application logic), and a database is the third tier
(storage).The web browser sends requests to the middle tier, which services
them by making queries and updates against the database and generates a
user interface.
 There are some who view a web application as a two-tier architecture. This
can be a "smart" client that performs all the work and queries a "dumb"
server, or a "dumb" client that relies on a "smart" server.

 MVC Pattern
PYTHON Page No :- 51 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
MVC Pattern When talking about applications that provides UI (web or desktop), we usually talk
about MVC architecture.

And as the name suggests, MVC pattern is based on three components: Model, View, and Controller.
Check our MVC tutorial here to know more.

DJANGO MVC - MVT Pattern The Model-View-Template (MVT) is slightly different from MVC.

In fact the main difference between the two patterns is that Django itself takes care of the Controller
part (Software Code that controls the interactions between the Model and View), leaving us with the
template.

The template is a HTML file mixed with Django Template Language (DTL).

The following diagram illustrates how each of the components of the MVT pattern interacts with
each other to serve a user request:

The developer provides the Model, the view and the template then just maps it to a URL URL and
Django does the magic to serve it to the user.

 Installing Django

Installing Django is very easy, but the steps required for its installation depends on
your operating system. Since Python is a platform-independent language, Django has
one package that works everywhere regardless of your operating system.
You can download the latest version of Django from the link
http://www.djangoproject.com/download.

PYTHON Page No :- 52 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
UNIX/Linux and Mac OS X Installation
You have two ways of installing Django if you are running Linux or Mac OS system −
 You can use the package manager of your OS, or use easy_install or pip if
installed.
 Install it manually using the official archive you downloaded before.
We will cover the second option as the first one depends on your OS distribution. If
you have decided to follow the first option, just be careful about the version of Django
you are installing.

Let's say you got your archive from the link above, it should be something like Django-
x.xx.tar.gz:
Extract and install.
$ tar xzvf Django-x.xx.tar.gz
$ cd Django-x.xx
$ sudo python setup.py install
You can test your installation by running this command −
$ django-admin.py --version
If you see the current version of Django printed on the screen, then everything is set.

Note − For some version of Django it will be django-admin the ".py" is removed.
Windows Installation
We assume you have your Django archive and python installed on your computer.
First, PATH verification.

On some version of windows (windows 7) you might need to make sure the Path
system variable has the path the following C:\Python27\;C:\Python27\Lib\site-
packages\django\bin\ in it, of course depending on your Python version.
Then, extract and install Django.

c:\>cd c:\Django-x.xx
Next, install Django by running the following command for which you will need
administrative privileges in windows shell "cmd" −
c:\Django-x.xx>python setup.py install

To test your installation, open a command prompt and type the following command −
c:\>django-admin.py --version
If you see the current version of Django printed on screen, then everything is set.
OR
Launch a "cmd" prompt and type python then −
c:\> python
>>> import django
>>> print django.get_version()

PYTHON Page No :- 53 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Setting up Database:

Django supports several major database engines and you can set up any of them
based on your comfort.
 MySQL (http://www.mysql.com/)
 PostgreSQL (http://www.postgresql.org/)
 SQLite 3 (http://www.sqlite.org/)
 Oracle (http://www.oracle.com/)
 MongoDb (https://django-mongodb-engine.readthedocs.org)
 GoogleAppEngine Datastore
(https://cloud.google.com/appengine/articles/django-nonrel)
You can refer to respective documentation to installing and configuring a database of
your choice.

● PostgreSQL (http://www.postgresql.org/) ● SQLite 3 (http://www.sqlite.org/) ● MySQL


(http://www.mysql.com/) ● Microsoft SQL Server (http://www.microsoft.com/sql/) ● Oracle
(http://www.oracle.com/database/)
We’re quite fond of PostgreSQL ourselves, for reasons outside the scope of this book, so we mention
it first. However, all those engines will work equally well with Django.

SQLite also deserves special notice: It’s an extremely simple in-process database engine that doesn’t
require any sort of server set up or configuration. It’s by far the easiest to set up if you just want to
play around with Django.

Using Django with PostgreSQL


If you’re using PostgreSQL, you’ll need the psycopg package available from
http://initd.org/projects/psycopg1. Make sure you use version 1, not version 2 (which is still in beta).
If you’re using PostgreSQL on Windows, you can find precompiled binaries of psycopg at
http://stickpeople.com/projects/python/ win-psycopg/.

Using Django with SQLite 3


You’ll need SQLite 3 — not version 2 — and the pysqlite package from
http://initd.org/tracker/pysqlite. Make sure you have pysqlite version 2.0.3 or higher.

Using Django with MySQL


Django requires MySQL 4.0 or above; the 3.x versions don’t support transactions, nested procedures,
and some other fairly standard SQL statements. You’ll also need the MySQLdb package

 Development Server :

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already,
and run the following commands:
python manage.py runserver
PYTHON Page No :- 54 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
You’ll see the following output on the command line: Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are
, →applied. Run 'python manage.py migrate' to apply them.
August 24, 2017 - 15:50:53 Django version 2.0, using settings 'mysite.settings' Starting development
server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Note: Ignore the warning about unapplied database migrations for now; we’ll deal with the database
shortly.
You’vestartedtheDjangodevelopmentserver,alightweightWebserverwrittenpurelyinPython.
We’veincludedthis with Django so you can develop things rapidly, without having to deal with
configuring a production server – such as Apache – until you’re ready for production.
2.3. Writing your first Django app, part 1 15
Django Documentation, Release 2.0.dev20170824180835
Now’s a good time to note: don’t use this server in anything resembling a production environment.
It’s intended only for use while developing. (We’re in the business of making Web frameworks, not
Web servers.) Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser.
You’ll see a “Congratulations!” page, with a rocket taking off. It worked!
Changingtheport By default, the runserver command starts the development server on the internal
IP at port 8000. If you want to change the server’s port, pass it as a command-line argument. For
instance, this command starts the server on port 8080:
python manage.py runserver 8080
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available
public IPs (which is useful if you are running Vagrant or want to show off your work on other
computers on the network), use:
python manage.py runserver 0:8000
0is a shortcut for0.0.0.0. Full docs for the development server can be found in the runserver
reference.
Automaticreloadingof runserver The development server automatically reloads Python code for each
request as needed. You don’t need to restart the serverforcodechangestotakeeffect. However,
someactionslikeaddingfilesdon’ttriggerarestart, soyou’llhaveto restart the server in these cases.

 Create a Project

Whether you are on Windows or Linux, just get a terminal or a cmd prompt and
navigate to the place you want your project to be created, then use this code −
$ django-admin startproject myproject
This will create a "myproject" folder with the following structure −
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
PYTHON Page No :- 55 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
wsgi.py
The Project Structure
The “myproject” folder is just your project container, it actually contains two elements

 manage.py − This file is kind of your project local django-admin for interacting
with your project via command line (start the development server, sync db...).
To get a full list of command accessible via manage.py you can use the code −
$ python manage.py help
 The “myproject” subfolder − This folder is the actual python package of your
project. It contains four files −
o __init__.py − Just for python, treat this folder as package.
o settings.py − As the name indicates, your project settings.
o urls.py − All links of your project and the function to call. A kind of ToC
of your project.
o wsgi.py − If you need to deploy your project over WSGI.

Setting Up Your Project


Your project is set up in the subfolder myproject/settings.py. Following are some
important options you might need to set −
DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets you
get more information about your project's error. Never set it to ‘True’ for a live
project. However, this has to be set to ‘True’ if you want the Django light server to
serve static files. Do it only in the development mode.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.sql',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Database is set in the ‘Database’ dictionary. The example above is for SQLite engine.
As stated earlier, Django also supports −
 MySQL (django.db.backends.mysql)
 PostGreSQL (django.db.backends.postgresql_psycopg2)
 Oracle (django.db.backends.oracle) and NoSQL DB
 MongoDB (django_mongodb_engine)

Before setting any new engine, make sure you have the correct db driver installed.
You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
Now that your project is created and configured make sure it's working −
PYTHON Page No :- 56 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
$ python manage.py runserver
You will get something like the following on running the above code −
Validating models...

0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

A view function, or view for short, is simply a Python function that takes a Web
request and returns a Web response.

This response can be the HTML contents of a Web page, or a redirect, or a 404 error,
or an XML document, or an image . . . or anything, really. The view itself contains
whatever arbitrary logic is necessary to return that response.

This code can live anywhere you want, as long as it’s on your Python path. There’s no
other requirement–no “magic,” so to speak. For the sake of putting the
code somewhere, the convention is to put views in a file called views.py, placed in
your project or application directory.

 Views.py

Here’s a view that returns the current date and time, as an HTML document:

from django.http import HttpResponse


import datetime

def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

Let’s step through this code one line at a time:

 First, we import the class HttpResponse from the django.http module, along
with Python’s datetime library.
 Next, we define a function called current_datetime. This is the view function.
Each view function takes an HttpRequest object as its first parameter, which is
typically named request.

PYTHON Page No :- 57 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Note that the name of the view function doesn’t matter; it doesn’t have to be
named in a certain way in order for Django to recognize it. We’re calling
it current_datetime here, because that name clearly indicates what it does.

 The view returns an HttpResponse object that contains the generated


response. Each view function is responsible for returning
an HttpResponse object.

 Models.py

 Once you have defined your models, you need to tell Django you’re going
to use those models. Do this by editing your settings file and changing
the INSTALLED_APPS setting to add the name of the module that contains
your models.py.
 For example, if the models for your application live in the
module myapp.models (the package structure that is created for an
application by the manage.py startapp script), INSTALLED_APPS should read,
in part:

 INSTALLED_APPS = [
 #...
 'myapp',
 #...
 ]

 When you add new apps to INSTALLED_APPS, be sure to


run manage.py migrate, optionally making migrations for them first
with manage.py makemigrations.

 Fields¶

 The most important part of a model – and the only required part of a model –
is the list of database fields it defines. Fields are specified by class attributes.
Be careful not to choose field names that conflict with the models
API like clean, save, ordelete.
 Example:

 from django.db import models



 class Musician(models.Model):
 first_name = models.CharField(max_length=50)
 last_name = models.CharField(max_length=50)
 instrument = models.CharField(max_length=100)

 class Album(models.Model):
PYTHON Page No :- 58 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
 artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
 name = models.CharField(max_length=100)
 release_date = models.DateField()
 num_stars = models.IntegerField()

 Django - Template System

Django makes it possible to separate python and HTML, the python goes in views and
HTML goes in templates. To link the two, Django relies on the render function and the
Django Template language.

The Render Function


This function takes three parameters −
 Request − The initial request.
 The path to the template − This is the path relative to the TEMPLATE_DIRS
option in the project settings.py variables.
 Dictionary of parameters − A dictionary that contains all variables needed in
the template. This variable can be created or you can use locals() to pass all
local variable declared in the view.

Django Template Language (DTL)


Django’s template engine offers a mini-language to define the user-facing layer of the
application.
Displaying Variables
A variable looks like this: {{variable}}. The template replaces the variable by the
variable sent by the view in the third parameter of the render function. Let's change
our hello.html to display today’s date −
hello.html
<html>

<body>
Hello World!!!<p>Today is {{today}}</p>
</body>

</html>
Then our view will change to −
def hello(request):

today = datetime.datetime.now().date()
return render(request, "hello.html", {"today" : today})
We will now get the following output after accessing the URL/myapp/hello −
Hello World!!!
Today is Sept. 11, 2015

PYTHON Page No :- 59 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
As you have probably noticed, if the variable is not a string, Django will use the __str__
method to display it; and with the same principle you can access an object attribute
just like you do it in Python. For example: if we wanted to display the date year, my
variable would be: {{today.year}}.
Filters
They help you modify variables at display time. Filters structure looks like the
following: {{var|filters}}.
Some examples −
 {{string|truncatewords:80}} − This filter will truncate the string, so you will see
only the first 80 words.
 {{string|lower}} − Converts the string to lowercase.
 {{string|escape|linebreaks}} − Escapes string contents, then converts line
breaks to tags.
You can also set the default for a variable.
Tags
Tags lets you perform the following operations: if condition, for loop, template
inheritance and more.
Tag if
Just like in Python you can use if, else and elif in your template −
<html>
<body>

Hello World!!!<p>Today is {{today}}</p>


We are
{% if today.day == 1 %}

the first day of month.


{% elif today == 30 %}

the last day of month.


{% else %}

I don't know.
{%endif%}

</body>
</html>
In this new template, depending on the date of the day, the template will render a
certain value.
Tag for
Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our
hello view to transmit a list to our template −
def hello(request):
today = datetime.datetime.now().date()
PYTHON Page No :- 60 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']


return render(request, "hello.html", {"today" : today, "days_of_week" :
daysOfWeek})
The template to display that list using {{ for }} −
<html>
<body>

Hello World!!!<p>Today is {{today}}</p>


We are
{% if today.day == 1 %}

the first day of month.


{% elif today == 30 %}

the last day of month.


{% else %}

I don't know.
{%endif%}

<p>
{% for day in days_of_week %}
{{day}}
</p>

{% endfor %}

</body>
</html>
And we should get something like −
Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun
Block and Extend Tags
A template system cannot be complete without template inheritance. Meaning when
you are designing your templates, you should have a main template with holes that
PYTHON Page No :- 61 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
the child's template will fill according to his own need, like a page might need a special
css for the selected tab.
Let’s change the hello.html template to inherit from a main_template.html.
main_template.html
<html>
<head>

<title>
{% block title %}Page Title{% endblock %}
</title>

</head>

<body>

{% block content %}
Body content
{% endblock %}

</body>
</html>
hello.html
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>


We are
{% if today.day == 1 %}

the first day of month.


{% elif today == 30 %}

the last day of month.


{% else %}

I don't know.
{%endif%}

<p>
{% for day in days_of_week %}
{{day}}
</p>

PYTHON Page No :- 62 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
{% endfor %}
{% endblock %}
In the above example, on calling /myapp/hello we will still get the same result as
before but now we rely on extends and block to refactor our code –

In the main_template.html we define blocks using the tag block. The title block will
contain the page title and the content block will have the page main content. In home.

html we use extends to inherit from the main_template.html then we fill the block
define above (content and title).
Comment Tag

 The comment tag helps to define comments into templates, not HTML
comments, they won’t appear in HTML page. It can be useful for
documentation or just commenting a line of code.

PYTHON Page No :- 63 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

Chapter -3
Interaction with Database
 Django Models: Basic Data Access

Once you’ve created a model, Django automatically provides a high-level Python API
for working with those models.

Try it out by running python manage.py shell from within your virtual environment
and typing the following:
>>> from books.models import Publisher
>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p1.save()
>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
... city='Cambridge', state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p2.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>
These few lines of code accomplish quite a bit. Here are the highlights:
 First, we import our Publisher model class. This lets us interact with the database
table that contains publishers.

 We create a Publisher object by instantiating it with values for each field –


name, address, etc.

 To save the object to the database, call its save() method. Behind the scenes, Django
executes an SQL INSERT statement here.

 To retrieve publishers from the database, use the attribute Publisher.objects, which
you can think of as a set of all publishers.

 Fetch a list of all Publisher objects in the database with the
statement Publisher.objects.all(). Behind the scenes, Django executes an
SQL SELECT statement here.

One thing is worth mentioning, in case it wasn’t clear from this example. When you’re
creating objects using the Django model API, Django doesn’t save the objects to the
database until you call the save()method:

PYTHON Page No :- 64 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

p1 = Publisher(...)
# At this point, p1 is not saved to the database yet!
p1.save()
# Now it is.
If you want to create an object and save it to the database in a single step, use
the objects.create()method. This example is equivalent to the example above:

>>> p1 = Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p2 = Publisher.objects.create(name="O'Reilly",
... address='10 Fawcett St.', city='Cambridge',
... state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>

Naturally, you can do quite a lot with the Django database API – but first, let’s take
care of a small annoyance.

Adding Model String Representations


When we printed out the list of publishers, all we got was this unhelpful display that
makes it difficult to tell the Publisher objects apart:

<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>


We can fix this easily by adding a method called __str__() to our Publisher class.
A __str__() method tells Python how to display a human-readable representation of
an object. You can see this in action by adding a __str__() method to the three
models:

from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

PYTHON Page No :- 65 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

def __str__(self):
return self.name

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

def __str__(self):
return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

def __str__(self):
return self.title
As you can see, a __str__() method can do whatever it needs to do in order to return a
representation of an object.

Here, the __str__() methods for Publisher and Book simply return the object’s name
and title, respectively, but the __str__() for Author is slightly more complex – it pieces
together the first_name and last_name fields, separated by a space.

The only requirement for __str__() is that it return a string object. If __str__() doesn’t
return a string object – if it returns, say, an integer – then Python will raise
a TypeError with a message like:

TypeError: __str__ returned non-string (type int).


For the __str__() changes to take effect, exit out of the Python shell and enter it again
with python manage.py shell. (This is the simplest way to make code changes take
effect.) Now the list of Publisherobjects is much easier to understand:

>>> from books.models import Publisher


>>> publisher_list = Publisher.objects.all()
>>> publisher_list
<QuerySet [<Publisher: Apress>, <Publisher: O'Reilly>]>
Make sure any model you define has a __str__() method – not only for your own
convenience when using the interactive interpreter, but also because Django uses the
output of __str__() in several places when it needs to display objects.

PYTHON Page No :- 66 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
Finally, note that __str__() is a good example of adding behavior to models.
/A Django model describes more than the database table layout for an object; it also
describes any functionality that object knows how to do.

__str__() is one example of such functionality – a model knows how to display itself.
Inserting and Updating Data
You’ve already seen this done: to insert a row into your database, first create an
instance of your model using keyword arguments, like so:

>>> p = Publisher(name='GNW Independent Publishing',


... address='123 Some Street',
... city='Hamilton',
... state_province='NSW',
... country='AUSTRALIA',
... website='http://djangobook.com/')

As we noted above, this act of instantiating a model class does not touch the
database. The record isn’t saved into the database until you call save(), like this:
>>> p.save()
In SQL, this can roughly be translated into the following:
INSERT INTO books_publisher
(name, address, city, state_province, country, website)
VALUES
('GNW Independent Publishing', '123 Some Street', 'Hamilton', 'NSW',
'Australia', 'http://djangobook.com/');

Because the Publisher model uses an auto incrementing primary key id, the initial call
to save() does one more thing: it calculates the primary key value for the record and
sets it to the id attribute on the instance:

>>> p.id
3 # this will differ based on your own data
Subsequent calls to save() will save the record in place, without creating a new record
(i.e., performing an SQL UPDATE statement instead of an INSERT):
>>> p.name = 'GNW Independent Publishing'
>>> p.save()

The preceding save() statement will result in roughly the following SQL:
UPDATE books_publisher SET
name = 'GNW Independent Publishing',
address='123 Some Street',
city='Hamilton',
state_province='NSW',
PYTHON Page No :- 67 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

country='INDIA',
website='http://djangobook.com/')
WHERE id = 3;

Yes, note that all of the fields will be updated, not just the ones that have been
changed. Depending on your application, this may cause a race condition. See
“Updating Multiple Objects in One Statement” below to find out how to execute this
(slightly different) query:

UPDATE books_publisher SET


name = 'GNW Independent Publishing'
WHERE id=3;
Selecting Objects
Knowing how to create and update database records is essential, but chances are that
the web applications you’ll build will be doing more querying of existing objects than
creating new ones.

We’ve already seen a way to retrieve every record for a given model:

>>> Publisher.objects.all()
<QuerySet [<Publisher: Apress>, <Publisher: O'Reilly>, <Publisher: GNW
Independent Publishing>]>
This roughly translates to this SQL:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher;

Notice that Django doesn’t use SELECT * when looking up data and instead lists all
fields explicitly.

This is by design: in certain circumstances SELECT * can be slower, and (more


important) listing fields more closely follows one tenet of the Zen of Python: “Explicit
is better than implicit.” For more on the Zen of Python, try typing import this at a
Python prompt.

Let’s take a close look at each part of this Publisher.objects.all() line:


 First, we have the model we defined, Publisher. No surprise here: when you want to
look up data, you use the model for that data.

 Next, we have the objects attribute. This is called a manager. Managers are discussed
in detail in Chapter 9. For now, all you need to know is that managers take care of all
table-level operations on data including, most important, data lookup.

PYTHON Page No :- 68 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 All models automatically get an objects manager; you’ll use it any time you want to
look up model instances.

 Finally, we have all(). This is a method on the objects manager that returns all the
rows in the database in a QuerySet – an object that represents a specific set of rows
from the database.

 Appendix C deals with QuerySets in detail.
Any database lookup is going to follow this general pattern – we’ll call methods on the
manager attached to the model we want to query against.

Updating Multiple Objects in One Statement


I pointed out in the “Inserting and Updating Data” section that the
model save() method updates allcolumns in a row.

Depending on your application, you may want to update only a subset of columns.

For example, let’s say we want to update the Apress Publisher to change the name
from 'Apress' to 'Apress Publishing'. Using save(), it would look something like this:
>>> p = Publisher.objects.get(name='Apress')
>>> p.name = 'Apress Publishing'
>>> p.save()
This roughly translates to the following SQL:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE name = 'Apress';

UPDATE books_publisher SET


name = 'Apress Publishing',
address = '2855 Telegraph Ave.',
city = 'Berkeley',
state_province = 'CA',
country = 'U.S.A.',
website = 'http://www.apress.com'
WHERE id = 1;

(Note that this example assumes Apress has a publisher ID of 1.) You can see in this
example that Django’s save() method sets all of the column values, not just
the name column.

If you’re in an environment where other columns of the database might change due to
some other process, it’s smarter to change only the column you need to change. To do
this, use the update() method on QuerySet objects. Here’s an example:

PYTHON Page No :- 69 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

>>> Publisher.objects.filter(id=1).update(name='Apress Publishing')


The SQL translation here is much more efficient and has no chance of race conditions:

UPDATE books_publisher
SET name = 'Apress Publishing'
WHERE id = 1;

The update() method works on any QuerySet, which means you can edit multiple
records in bulk. Here’s how you might change the country from 'U.S.A.' to USA in
each Publisher record:

>>> Publisher.objects.all().update(country='USA')
3

The update() method has a return value – an integer representing how many records
changed. In the above example, we got 3.

Deleting Objects
To delete an object from your database, simply call the object’s delete() method:
>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
(1, {'books.Publisher': 1})
>>> Publisher.objects.all()
<QuerySet [<Publisher: Apress>, <Publisher: GNW Independent Publishing>]>

Note the return value from Django when you delete an object – Django first lists the
total number of records that will be affected (in this case one) and a dictionary
containing each of the models (tables) affected and how many records were deleted
in each table.

You can also delete objects in bulk by calling delete() on the result of any QuerySet.
This is similar to the update() method we showed in the last section:
>>> Publisher.objects.filter(country='USA').delete()
(1, {'books.Publisher': 1})
>>> Publisher.objects.all().delete()
(1, {'books.Publisher': 1})
>>> Publisher.objects.all()
<QuerySet []>

Be careful deleting your data! As a precaution against deleting all of the data in a
particular table, Django requires you to explicitly use all() if you want to
delete everything in your table. For example, this won’t work:
PYTHON Page No :- 70 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

>>> Publisher.objects.delete()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Manager' object has no attribute 'delete'

But it’ll work if you add the all() method:


>>> Publisher.objects.all().delete()

Note, If you’re just deleting a subset of your data, you don’t need to
include all(). To repeat a previous example:

>>> Publisher.objects.filter(country='USA').delete()

CHAPTER – 4
Django Admin Site & Forms, Views and URLConfs
PYTHON Page No :- 71 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

 Creating & Activating Admin Interface :-


 Django provides a ready-to-use user interface for administrative activities. We
all know how an admin interface is important for a web project. Django
automatically generates admin UI based on your project models.

 Starting the Admin Interface


The Admin interface depends on the django.countrib module. To have it
working you need to make sure some modules are imported in the
INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the
myproject/settings.py file.

 For INSTALLED_APPS make sure you have −


 INSTALLED_APPS = (
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myapp',
 )
 For MIDDLEWARE_CLASSES −
 MIDDLEWARE_CLASSES = (
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 )
 Before launching your server, to access your Admin Interface, you need to
initiate the database −
 $ python manage.py migrate
 syncdb will create necessary tables or collections depending on your db type,
necessary for the admin interface to run. Even if you don't have a superuser,
you will be prompted to create one.
 If you already have a superuser or have forgotten it, you can always create
one using the following code −
 $ python manage.py createsuperuser
PYTHON Page No :- 72 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

 Now to start the Admin Interface, we need to make sure we have configured
a URL for our admin interface. Open the myproject/url.py and you should
have something like −
 from django.conf.urls import patterns, include, url

 from django.contrib import admin
 admin.autodiscover()

 urlpatterns = patterns('',
 # Examples:
 # url(r'^$', 'myproject.views.home', name = 'home'),
 # url(r'^blog/', include('blog.urls')),

 url(r'^admin/', include(admin.site.urls)),
 )
 Now just run the server.
 $ python manage.py runserver
 And your admin interface is accessible at: http://127.0.0.1:8000/admin/

 Creating Super users and groups:-

You already created your first user when we looked at the Django admin site in
tutorial 4 (this was a superuser, created with the command python manage.py
createsuperuser). Our superuser is already authenticated and has all permissions, so
we'll need to create a test user to represent a normal site user. We'll be using the
admin site to create our locallibrary groups and website logins, as it is one of the
quickest ways to do so.
Note: You can also create users programmatically, as shown below. You would have to
do this, for example, if developing an interface to allow users to create their own
logins (you shouldn't give users access to the admin site).

from django.contrib.auth.models import User

# Create user and save to the database


user = User.objects.create_user('myusername', 'myemail@crazymail.com',
'mypassword')

# Update fields and then save again


user.first_name = 'John'
user.last_name = 'Citizen'

PYTHON Page No :- 73 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

user.save()

Below we'll first create a group and then a user. Even though we don't have any
permissions to add for our library members yet, if we need to later, it will be much
easier to add them once to the group than individually to each member.

Start the development server and navigate to the admin site in your local web browser
(http://127.0.0.1:8000/admin/). Login to the site using the credentials for your
superuser account. The top level of the Admin site displays all of your models, sorted
by "django application". From the Authentication and Authorisation section you can
click the Usersor Groups links to see their existing records.

First lets create a new group for our library members.

1. Click the Add button (next to Group) to create a new Group; enter
the Name "Library Members" for the group.

PYTHON Page No :- 74 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

2. We don't need any permissions for the group, so just press SAVE (you will be
taken to a list of groups).
Now lets create a user:

1. Navigate back to the home page of the admin site

2. Click the Add button next to Users to open the Add user dialog.
3. Enter an appropriate Username and Password/Password confirmation for
your test user
4. Press SAVE to create the user.

The admin site will create the new user and immediately take you to a Change
userscreen where you can change your username and add information for the User
model's optional fields. These fields include the first name, last name, email address,
the users status and permissions (only the Active flag should be set). Further down
you can specify the user's groups and permissions, and see important dates related to

the user (e.g. their join date and last login date).
5. In the Groups section, select Library Member group from the list of Available
groups, and then press the right-arrow between the boxes to move it into the Chosen

groupsbox.
6. We don't need to do anything else here, so just select SAVE again, to go to the
list of users.

Creating forms in Django, is really similar to creating a model. Here again, we just
need to inherit from Django class and the class attributes will be the form fields. Let's
PYTHON Page No :- 75 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

add a forms.py file in myapp folder to contain our app forms. We will create a login
form.
myapp/forms.py

#-*- coding: utf-8 -*-

from django import forms

class LoginForm(forms.Form):

user = forms.CharField(max_length = 100)

password = forms.CharField(widget = forms.PasswordInput())

As seen above, the field type can take "widget" argument for html rendering; in our
case, we want the password to be hidden, not displayed. Many others widget are
present in Django: DateInput for dates, CheckboxInput for checkboxes, etc.

 Using Form in a View:-


There are two kinds of HTTP requests, GET and POST. In Django, the request object
passed as parameter to your view has an attribute called "method" where the type of
the request is set, and all data passed via POST can be accessed via the request.POST
dictionary.
Let's create a login view in our myapp/views.py −

#-*- coding: utf-8 -*-


from myapp.forms import LoginForm

def login(request):
username = "not logged in"

if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)

if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = Loginform()

return render(request, 'loggedin.html', {"username" : username})

PYTHON Page No :- 76 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

The view will display the result of the login form posted through the loggedin.html.
To test it, we will first need the login form template. Let's call it login.html.

<html>
<body>

<form name = "form" action = "{% url "myapp.views.login" %}"


method = "POST" >{% csrf_token %}

<div style = "max-width:470px;">


<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Identifiant" name = "username" />
</center>
</div>

<br>

<div style = "max-width:470px;">


<center>
<input type = "password" style = "margin-left:20%;"
placeholder = "password" name = "password" />
</center>
</div>

<br>

<div style = "max-width:470px;">


<center>

<button style = "border:0px; background-color:#4285F4; margin-top:8%;


height:35px; width:80%;margin-left:19%;" type = "submit"
value = "Login" >
<strong>Login</strong>
</button>

</center>
</div>

</form>

</body>
</html>

PYTHON Page No :- 77 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 Get & Post Method in Form:-

GET and POST are the only HTTP methods to use when dealing with forms.

Django’s login form is returned using the POST method, in which the browser bundles
up the form data, encodes it for transmission, sends it to the server, and then receives
back its response.

GET, by contrast, bundles the submitted data into a string, and uses this to compose a
URL. The URL contains the address where the data must be sent, as well as the data
keys and values. You can see this in action if you do a search in the Django
documentation, which will produce a URL of the
form https://docs.djangoproject.com/search/?q=forms&release=1.

GET and POST are typically used for different purposes.

Any request that could be used to change the state of the system - for example, a
request that makes changes in the database - should use POST. GET should be used
only for requests that do not affect the state of the system.

GET would also be unsuitable for a password form, because the password would
appear in the URL, and thus, also in browser history and server logs, all in plain text.
Neither would it be suitable for large quantities of data, or for binary data, such as an
image. A Web application that uses GET requests for admin forms is a security risk: it
can be easy for an attacker to mimic a form’s request to gain access to sensitive parts
of the system. POST, coupled with other protections like Django’s CSRF
protection offers more control over access.

On the other hand, GET is suitable for things like a web search form, because the URLs
that represent a GET request can easily be bookmarked, shared, or resubmitted.

 Validation in Form:-

Form validation happens when the data is cleaned. If you want to customize this
process, there are various places to make changes, each one serving a different
purpose. Three types of cleaning methods are run during form processing. These are
normally executed when you call the is_valid() method on a form. There are other
things that can also trigger cleaning and validation (accessing the errors attribute or
calling full_clean() directly), but normally they won’t be needed.

In general, any cleaning method can raise ValidationError if there is a problem with
the data it is processing, passing the relevant information to
the ValidationError constructor. See below for the best practice in

PYTHON Page No :- 78 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
raising ValidationError. If no ValidationError is raised, the method should return the
cleaned (normalized) data as a Python object.

Most validation can be done using validators - simple helpers that can be reused
easily. Validators are simple functions (or callables) that take a single argument and
raise ValidationError on invalid input. Validators are run after the
field’s to_python and validate methods have been called.

Validation of a form is split into several steps, which can be customized or overridden:

 The to_python() method on a Field is the first step in every validation. It


coerces the value to a correct datatype and raises ValidationError if that is not
possible. This method accepts the raw value from the widget and returns the
converted value. For example, a FloatField will turn the data into a
Python float or raise a ValidationError.

 The validate() method on a Field handles field-specific validation that is not


suitable for a validator. It takes a value that has been coerced to a correct
datatype and raises ValidationError on any error. This method does not return
anything and shouldn’t alter the value. You should override it to handle
validation logic that you can’t or don’t want to put in a validator.

 The run_validators() method on a Field runs all of the field’s validators and
aggregates all the errors into a singleValidationError. You shouldn’t need to
override this method.

 ModelForms :-

Creating a Form class using the approach described above is very flexible, allowing you
to create whatever sort of form page you like and associate it with any model or
models.

However if you just need a form to map the fields of a single model then your model
will already define most of the information that you need in your form: fields, labels,
help text, etc.

Rather than recreating the model definitions in your form, it is easier to use
the ModelForm helper class to create the form from your model. This ModelForm can
then be used within your views in exactly the same way as an ordinary Form.

A basic ModelForm containing the same field as our original RenewBookForm is


shown below. All you need to do to create the form is add class Meta with the
associated model (BookInstance) and a list of the model fields to include in the form
(you can include all fields using fields = '__all__', or you can use exclude (instead
of fields) to specify the fields not to include from the model).

PYTHON Page No :- 79 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

from django.forms import ModelForm


from .models import BookInstance

class RenewBookModelForm(ModelForm):
class Meta:
model = BookInstance
fields = ['due_back',]

Note: This might not look like all that much simpler than just using a Form (and it isn't
in this case, because we just have one field). However if you have a lot of fields, it can
reduce the amount of code quite significantly!

The rest of the information comes from the model field definitions (e.g. labels,
widgets, help text, error messages). If these aren't quite right, then we can override
them in our class Meta, specifying a dictionary containing the field to change and its
new value.

For example, in this form we might want a label for our field of "Renewal date"
(rather than the default based on the field name: Due date), and we also want our
help text to be specific to this use case.

The Meta below shows you how to override these fields, and you can similarly
set widgets and error_messages if the defaults aren't sufficient.

class Meta:
model = BookInstance
fields = ['due_back',]
labels = { 'due_back': _('Renewal date'), }
help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'),
}

To add validation you can use the same approach as for a normal Form — you define a
function named clean_field_name() and raise ValidationError exceptions for invalid
values. The only difference with respect to our original form is that the model field is
named due_back and not "renewal_date".

from django.forms import ModelForm


from .models import BookInstance

class RenewBookModelForm(ModelForm):
def clean_due_back(self):
data = self.cleaned_data['due_back']

#Check date is not in past.

PYTHON Page No :- 80 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

if data < datetime.date.today():


raise ValidationError(_('Invalid date - renewal in past'))

#Check date is in range librarian allowed to change (+4 weeks)


if data > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))

# Remember to always return the cleaned data.


return data

class Meta:
model = BookInstance
fields = ['due_back',]
labels = { 'due_back': _('Renewal date'), }
help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'),
}

 Understanding View Layer :-

 A view function, or “view” for short, is simply a Python function that takes a
web request and returns a web response. This response can be the HTML
contents of a Web page, or a redirect, or a 404 error, or an XML document, or
an image, etc. Example: You use view to create web pages, note that you need
to associate a view to a URL to see it as a web page.
 In Django, views have to be created in the app views.py file.

 Simple View
 We will create a simple view in myapp to say "welcome to my app!"
 See the following view −
 from django.http import HttpResponse

 def hello(request):
 text = """<h1>welcome to my app !</h1>"""
 return HttpResponse(text)

Django has the concept of “views” to encapsulate the logic responsible for processing
a user’s request and for returning the response. Find all you need to know about views
via the links below:

 The basics: URLconfs | View functions | Shortcuts | Decorators

PYTHON Page No :- 81 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Reference: Built-in Views | Request/response objects | TemplateResponse
objects
 File uploads: Overview | File objects | Storage API | Managing files | Custom
storage
 Class-based views: Overview | Built-in display views | Built-in editing
views | Using mixins | API reference | Flattened index
 Advanced: Generating CSV | Generating PDF
 Middleware: Overview | Built-in middleware classes

 Requesting Webpage via URL :-

Django uses request and response objects to pass state through the system.

When a page is requested, Django creates an HttpRequest object that contains


metadata about the request. Then Django loads the appropriate view, passing
the HttpRequest as the first argument to the view function. Each view is responsible
for returning an HttpResponse object.

This document explains the APIs for HttpRequest and HttpResponse objects, which
are defined in the django.httpmodule.

 HttpRequest objects
class HttpRequest[source]¶

Attributes¶

All attributes should be considered read-only, unless stated otherwise.

HttpRequest.scheme¶

A string representing the scheme of the request (http or https usually).

HttpRequest.body¶

The raw HTTP request body as a byte string. This is useful for processing data in
different ways than conventional HTML forms: binary images, XML payload etc.
For processing conventional form data, use HttpRequest.POST.

You can also read from an HttpRequest using a file-like interface.


See HttpRequest.read().

HttpRequest.path¶

PYTHON Page No :- 82 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
A string representing the full path to the requested page, not including the
scheme or domain.

Example: "/music/bands/the_beatles/"

HttpRequest.path_info¶

Under some Web server configurations, the portion of the URL after the host
name is split up into a script prefix portion and a path info portion.
The path_info attribute always contains the path info portion of the path, no
matter what Web server is being used. Using this instead of path can make
your code easier to move between test and deployment servers.

For example, if the WSGIScriptAlias for your application is set to "/minfo",


then path might be "/minfo/music/bands/the_beatles/" and path_info would
be "/music/bands/the_beatles/".

HttpRequest.method¶

A string representing the HTTP method used in the request. This is guaranteed
to be uppercase. For example:

if request.method == 'GET':

do_something()

elif request.method == 'POST':

do_something_else()

 Rendering HttpResponse to Template

Template will be rendered via view. But this time we do not need to hardcode the
html inside our python code. As we already separated the html and now it is an
individual file.

To render the template we created follow these steps.

 Come inside views.py file that we created. And write the following code.

PYTHON Page No :- 83 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

from django.http import HttpResponse


#mporting loading from django template
from django.template import loader
#our view which is a function named index
def index(request):

#getting our template


template = loader.get_template('index.html')

#rendering the template in HttpResponse


return HttpResponse(template.render())

 Now lets try running our project. So again run the command python
manage.py runserver in the terminal inside PyCharm.
 http://127.0.0.1:8000/firsttemplate/
 Go to the above URL and you will see the template we created.

 Getting a response :-
Of course, that’s only half the battle; when you’re working in a view, you also need to
return an HttpResponse, usually by doing something like (returning to the first
example above, where we loaded a template in the variable t and created
a Context named c):

return HttpResponse(t.render(c))

And that makes the whole thing even more tedious, which is why the documentation
goes to great pains to point out the render_to_response() shortcut.
Using render_to_response(), everything gets much simpler:

PYTHON Page No :- 84 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

return render_to_response('my_template.html',
{ 'object_list': SomeModel.objects.all() })

This collapses the whole process of loading a template, creating a Context, rendering
the template and creating an HttpResponse into one easy step. I’d hope that anyone
who spends more than an hour or two playing with Django picks up on this, but it’s
worth pointing out in case you’ve never run across it.
 TemplateResponse objects:-
class TemplateResponse[source]¶

TemplateResponse is a subclass of SimpleTemplateResponse that knows


about the current HttpRequest.

Methods¶
TemplateResponse.__init__(request, template, context=None, content_type=None, s
tatus=None, charset=None, using=None)[source]¶

Instantiates a TemplateResponse object with the given request, template,


context, content type, HTTP status, and charset.

request

An HttpRequest instance.

template
A backend-dependent template object (such as those returned
by get_template()), the name of a template, or a list of template names.

context
A dict of values to add to the template context. By default, this is an empty
dictionary.

content_type
The value included in the HTTP Content-Type header, including the MIME type
specification and the character set encoding. If content_type is specified, then
its value is used. Otherwise, DEFAULT_CONTENT_TYPE is used.

status
The HTTP status code for the response.

PYTHON Page No :- 85 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
charset
The charset in which the response will be encoded. If not given it will be
extracted from content_type, and if that is unsuccessful,
the DEFAULT_CHARSET setting will be used.

using
The NAME of a template engine to use for loading the template.

PYTHON Page No :- 86 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

Chapter -5
Session and Cookies & Testing and Deploying web
application
 Cookies :-
 Sometimes you might want to store some data on a per-site-visitor basis as
per the requirements of your web application. Always keep in mind, that
cookies are saved on the client side and depending on your client browser
security level, setting cookies can at times work and at times might not.

 Getting and Setting Cookies


When dealing with persistence in Django, most of the time you’ll want to use the
higher-level session and/or user frameworks discussed a little later in this chapter.
However, first look at how to read and write cookies at a low level.

This should help you understand how the rest of the tools discussed in the chapter
actually work, and it will come in handy if you ever need to play with cookies directly.

Reading cookies that are already set is simple. Every HttpRequest object has
a COOKIES object that acts like a dictionary; you can use it to read any cookies that
the browser has sent to the view:

def show_color(request):
if "favorite_color" in request.COOKIES:
return HttpResponse("Your favorite color is %s" % \
request.COOKIES["favorite_color"])
else:
return HttpResponse("You don't have a favorite color.")

Writing cookies is slightly more complicated. You need to use


the set_cookie() method on an HttpResponse object. Here’s an example that sets
the favorite_color cookie based on a GET parameter:

def set_color(request):
if "favorite_color" in request.GET:

# Create an HttpResponse object...


response = HttpResponse("Your favorite color is now %s" % \
request.GET["favorite_color"])
PYTHON Page No :- 87 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)

# ... and set a cookie on the response


response.set_cookie("favorite_color",
request.GET["favorite_color"])

return response

else:
return HttpResponse("You didn't give a favorite color.")

 Sessions:-

This session framework lets you store and retrieve arbitrary data on a per-site visitor
basis. It stores data on the server side and abstracts the sending and receiving of
cookies. Cookies use only a hashed session ID – not the data itself – thus protecting
you from most of the common cookie problems.

Let’s look at how to enable sessions and use them in views.

Enabling Sessions
Sessions are implemented via a piece of middleware (see Chapter 17) and a Django
model. To enable sessions, you’ll need to follow these steps:

1. Edit your MIDDLEWARE_CLASSES setting and make


sure MIDDLEWARE_CLASSES contains 'django.contrib.sessions.middleware.Sessio
nMiddleware' .
2. Make sure 'django.contrib.sessions' is in your INSTALLED_APPS setting (and
run manage.py syncdb if you have to add it).

The default skeleton settings created by startproject have both of these bits already
installed, so unless you’ve removed them, you probably don’t have to change anything
to get sessions to work.

If you don’t want to use sessions, you might want to remove


the SessionMiddleware line
from MIDDLEWARE_CLASSES and 'django.contrib.sessions' from
your INSTALLED_APPS . It will save you only a small amount of overhead, but every
little bit counts.

PYTHON Page No :- 88 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
 Using Sessions in Views
When SessionMiddleware is activated, each HttpRequest object – the first argument
to any Django view function – will have a session attribute, which is a dictionary-like
object. You can read it and write to it in the same way you’d use a normal dictionary.
For example, in a view you could do stuff like this:

# Set a session value:


request.session["fav_color"] = "blue"

# Get a session value -- this could be called in a different view,


# or many requests later (or both):
fav_color = request.session["fav_color"]

# Clear an item from the session:


del request.session["fav_color"]

# Check if the session has a given key:


if "fav_color" in request.session:
...
You can also use other dictionary methods
like keys() and items() on request.session .

There are a couple of simple rules for using Django’s sessions effectively:

 Use normal Python strings as dictionary keys on request.session (as opposed to


integers, objects, etc.).
 Session dictionary keys that begin with an underscore are reserved for internal use
by Django. In practice, the framework uses only a small number of underscore-
prefixed session variables, but unless you know what they all are (and you are
willing to keep up with any changes in Django itself), staying away from underscore
prefixes will keep Django from interfering with your application.

For example, don’t use a session key called _fav_color , like this:

request.session['_fav_color'] = 'blue' # Don't do this!


 Don’t replace request.session with a new object, and don’t access or set its
attributes. Use it like a Python dictionary. Examples:
 request.session = some_other_object # Don't do this!

 request.session.foo = 'bar' # Don't do this!

PYTHON Page No :- 89 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

Let’s take a look at a few quick examples. This simplistic view sets
a has_commented variable to True after a user posts a comment. It’s a simple (if not
particularly secure) way of preventing a user from posting more than one comment:

def post_comment(request):
if request.method != 'POST':
raise Http404('Only POSTs are allowed')

if 'comment' not in request.POST:


raise Http404('Comment not submitted')

if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")

c = comments.Comment(comment=request.POST['comment'])
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')

 Using Sessions Outside of Views


Internally, each session is just a normal Django model defined
in django.contrib.sessions.models .

Each session is identified by a more-or-less random 32-character hash stored in a


cookie.

Because it’s a normal model, you can access sessions using the normal Django
database API:

>>> from django.contrib.sessions.models import Session


>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
>>> s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)

You’ll need to call get_decoded() to get the actual session data. This is necessary
because the dictionary is stored in an encoded format:

PYTHON Page No :- 90 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

>>> s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
>>> s.get_decoded()
{'user_id': 42}

 Python’s UnitTest2 Library :-


unittest2 is a backport of additional features added to the Python testing framework
in Python 2.7 and onwards. It is tested to run on Python 2.6, 2.7, and 3.*. Latest
version can be downloaded from https://pypi.python.org/pypi/unittest2
To use unittest2 instead of unittest, simply replace import unittest with import
unittest2.
Classes in unittest2 derive from the appropriate classes in unittest, so it should be
possible to use the unittest2 test running infrastructure without having to switch all
your tests to using unittest2 immediately. In case you intend to implement new
features, subclass your testcase from unittest2.TestCase instead of unittest.TestCase
The following are the new features of unittest2 −
 addCleanups for better resource management
 Contains many new assert methods
 assertRaises as context manager, with access to the exception afterwards
 Has module level fixtures such as setUpModule and tearDownModule
 Includes load_tests protocol for loading tests from modules or packages
 startTestRun and stopTestRun methods on TestResult
 If the unittest handler is called but signal.SIGINT handler isn’t installed, then it
calls for the default handler. This will normally be the expected behavior by
code that replaces an installed handler and delegates to it. For individual tests
that need unittest control-c handling disabled, the removeHandler() decorator
can be used.
 The following utility functions enable control-c handling functionality within
test frameworks −

 unittest.installHandler()
 Install the control-c handler. When a signal.SIGINT is received all registered
results have TestResult.stop() called.

PYTHON Page No :- 91 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

 unittest.registerResult(result)
 Register a TestResult object for control-c handling. Registering a result stores
a weak reference to it, so it doesn’t prevent the result from being garbage
collected.

 unittest.removeResult(result)
 Remove a registered result. Once a result has been removed then
TestResult.stop() will no longer be called on that result object in response to a
control-c.

 unittest.removeHandler(function = None)
 When called without arguments, this function removes the control-c handler if
it has been installed. This function can also be used as a test decorator to
temporarily remove the handler whilst the test is being executed.
 Testing Django :-
Testing a website is a complex task, because it is made of several layers of logic – from
HTTP-level request handling, queries models, to form validation and processing, and
template rendering.

Types of testing

There are numerous types, levels, and classifications of tests and testing approaches.
The most important automated tests are:

Unit tests

Verify functional behavior of individual components, often to class and


function level.

Regression tests
Tests that reproduce historic bugs. Each test is initially run to verify that the
bug has been fixed, and then re-run to ensure that it has not been
reintroduced following later changes to the code.

Integration tests
Verify how groupings of components work when used together. Integration
tests are aware of the required interactions between components, but not

PYTHON Page No :- 92 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
necessarily of the internal operations of each component. They may cover
simple groupings of components through to the whole website.

 Test structure overview

Before we go into the detail of "what to test", let's first briefly look
at where and how tests are defined.
Django uses the unittest module’s built-in test discovery, which will discover tests
under the current working directory in any file named with the pattern test*.py.
Provided you name the files appropriately, you can use any structure you like. We
recommend that you create a module for your test code, and have separate files for
models, views, forms, and any other types of code you need to test. For example:

catalog/
/tests/
__init__.py
test_models.py
test_forms.py
test_views.py

Create a file structure as shown above in your LocalLibrary project.


The __init__.py should be an empty file (this tells Python that the directory is a
package). You can create the three test files by copying and renaming the skeleton
test file /catalog/tests.py.

Open /catalog/tests/test_models.py. The file should import django.test.TestCase, as


shown:

from django.test import TestCase

# Create your tests here.

How to run the tests

The easiest way to run all the tests is to use the command:

PYTHON Page No :- 93 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)

python3 manage.py test

This will discover all files named with the pattern test*.py under the current directory
and run all tests defined using appropriate base classes (here we have a number of
test files, but only /catalog/tests/test_models.py currently contains any tests.) By
default the tests will individually report only on test failures, followed by a test
summary.

 Deploying Django Application on GitHub / Amazon Web Services :-


Django is a Python framework that lets you create web applications easily. For
information on Django, visit the Django project website.

 Before You Begin

1. Forking the Sample App from GitHub


2. Creating the Application in Pipelines
3. Adding your Deployment Steps
4. Adding your EC2 Instance
5. Deploying the Application
6. Enabling Automatic Builds and Deployments
7. Testing Automatic Deployments

 Ensure you have the following:

 Git installed on your development machine.


 A Pipelines account. Register for a Pipelines account.
 A GitHub account. Register for a GitHub account.
 An Amazon EC2 account. For steps to set up your EC2 account, see How to Set Up an
AWS EC2 instance.

1. Forking the Sample App from GitHub

If you already have a Django application, create a GitHub repository for your
application, and add your code to your repository. Then, skip to Step 2 of this tutorial.

If you are using the sample Django application, do the following:

1. Log into your GitHub account.


2. Open the sample Django application in the GitHub repository.
PYTHON Page No :- 94 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
3. Click Fork. The Example-Django-App repository is copied to your GitHub account.

4. In your terminal, navigate to a directory where you want to store the code for the
application. Then, clone the repository using the following syntax:

~~~ git clone https://github.com/YOUR_GITHUB_USERNAME/nodejsbuilddeploy.git


~~~

Next, we will link the GitHub repository to Pipelines. Once linked, your application is
automatically built every time you make changes to the application.

2. Creating the Application in Pipelines

1. Log into your Pipelines account. The home page for your account opens.
2. On the top right, click New App. The New App page opens.
3. In the Name your app field, type a name for your app.
4. Click GitHub. You are prompted to allow Pipelines to access your GitHub repositories.
Once you grant access, the New App page opens.
PYTHON Page No :- 95 Gaurav K Sardhara :- 9067351366
(Affiliated to Saurashtra University & Gujarat Technological University)
5. Click Use GitHub. A list of your GitHub repositories is shown.
6. Select the Example-Django-App repository that you forked in the earlier step. The list
of branches for the repository is shown.
7. Select the master branch, and click I’m Done. The Configure your Build Steps section
expands.
8. Build Steps are instructions that describe how to build and package your application.
For this tutorial, in the PkgInclude section, add an asterisk (*). This includes all the
application’s files in the build.
9. Click Done. A summary of your build configuration is shown.
10. From the Build Image menu, select Distelli Python (Docker), and click Start Build. The
application is added to your account, and the build begins. To see the status of the
build, click Go to Build.

Now that the application is added to Pipelines, we can deploy it to your EC2 instance.

3. Adding your Deployment Steps

1. In your Pipelines account, in the top menu, click Applications. The list of your
applications opens.
2. Click the name of your application. The application’s settings page opens.

PYTHON Page No :- 96 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
3. Click the Manifest tab, and expand the Deployment Manifest section. In this section,
we provide the commands that your server runs when the application is deployed.
4. In the PreInstall section, add the commands to install Python and Django on the
server: ~~~ sudo apt-get update sudo apt-get install python-pip sudo pip install django
~~~
5. In the Exec section, add the command to start the application: ~~~ python manager.py
runserver 0.0.0.0:8080 ~~~

In the next step, we add an environment for your application, and launch an EC2
instance to deploy the application to.

4. Adding your EC2 Instance

If you have set up an Amazon EC2 account, you can launch a new EC2 instance for
your application from within Pipelines.

If you have not set up your Amazon EC2 account, see How to Set Up Amazon EC2 for
steps to set one up.

1. In your Pipelines account, from the top menu, click Applications. The list of your
applications opens.
2. Click the name of your application. The application’s settings page opens.
3. Click the Environments tab, then click Create Environment, as in the example below:

PYTHON Page No :- 97 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
4. In the top menu, click Servers. The Servers page opens.
5. Click Add Server. The New Server page opens.
6. Click Launch an EC2 instance. Follow the steps to choose your options:
o Configuration Type: Select New EC2 Configuration.
o AWS Region: Select a region that’s closest to you.
o Instance Type: For this tutorial, select a General Purpose instance that works for
you.
o OS Image: Select Ubuntu.

Depending on your EC2 configuration, select additional options, such as your Virtual
Private Cloud (VPC), EC2 key pairs, and so on.
7. In the Add Tags, User Data and Environments section, select the environment that you
just created.
8. When you have finished selecting your EC2 configuration, click Launch to start the
instance.

In the next step, we will deploy the application to your server.

5. Deploying the Application

Every time your application is built, Pipelines creates a release. When you are ready to
deploy the application, you select a release that is deployed to your server. To deploy
the application:

1. From the top menu, click Applications. The list of your applications opens.
2. Click the name of your application. The application’s settings page opens.
3. Click New Deployment (the “rocket” icon). The New Deployment page opens.
4. Click Deploy a Release. You are prompted to choose your application.
5. Click your application’s name, and select the latest release.
6. When prompted to select an environment, select the environment you created in the
previous step, and click All Done.
7. Click Deploy. Your application is deployed.
8. To test the application, navigate to http://<SERVER-IP-ADDRESS>:8080,
where <SERVER-IP-ADDRESS> is the IP address of your EC2 instance.

6. Enabling Automatic Builds and Deployments

To enable automatic deployments for your application, you create an application


pipeline to ensure that all successful builds are automatically deployed to your
servers.

PYTHON Page No :- 98 Gaurav K Sardhara :- 9067351366


(Affiliated to Saurashtra University & Gujarat Technological University)
1. From the top menu, click Applications. The list of your applications opens.
2. Click the name of your application. The application’s settings page opens.
3. On the right, under App Pipeline, ensure that the Auto Build option is enabled.
4. To add a step to the pipeline, click Add Step, and select the environment you created
earlier.
5. Click Add. The environment is added to the pipeline.
6. To enable automatic deployments, enable the Auto Deploy check box, and from the
menu, select If the Build Succeeds.

7. Testing Automatic Deployments

Now, every time you push new code to your GitHub repository, Pipelines builds your
application and deploys it to your server. Let’s make a small code change, and push it
to the repository to observe this automation process in action.

1. On your development machine, navigate to the folder where you added the sample
application, and from the templates folder, open index.html in a text editor.
2. Change some text in the HTML file, and save the file.
3. In your terminal, push the code to your GitHub repository, using the following

commands: ~~~ git add . git commit -m “Testing Distelli auto build” git push ~~~
4. Your changed application is automatically built and deployed.

PYTHON Page No :- 99 Gaurav K Sardhara :- 9067351366

You might also like