Programming in Python
Programming in Python
BCA – SEMESTER -6
SUB :- PYTHON
CS – 14 : PYTHON–BCA –SEM -6
CHAPTER-1
Introduction to Python and Python Syntax, Language
Components / Collections & Functions
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.
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".
Installing python :
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 −
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
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
or
or
IDLE:
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
Hello, Python!
You can type a comment on the same line after a statement or expression −
# 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.
$ 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 −
Hello, Python!
$ python test.py
Hello, Python!
On Windows
C:\Python34>Python test.py
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!")
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
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.
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 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:
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.
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.
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}'.
The following diagram with an example usage depicts how the string method
"format" works works for positional parameters:
In the following example we demonstrate how keyword parameters can be used with
the format method:
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:
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.
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 :
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.
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.
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
Examples
Here are some examples of numbers −
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 :
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
>>>
print Function
The arguments of the print function are the following ones:
>>> 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:
>>> 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:
if True:
print "True"
else:
print "False"
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:
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 :
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 :
if expression:
statement(s)
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!"
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
else:
print "4 - Got a false expression value"
print var
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
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!"
Current Letter : P
Current Letter : y
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)
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 −
Logical Operator :
There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then
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
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':
break
print 'Current Letter :', letter
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
Example
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
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)
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.
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.
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.
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 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)
Defining Function :
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
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
There is one more thing we will cover in this (monsterously huge) lesson - passing
parameters to a function. Thinkback to how we defined functions:
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.
CHAPTER-2
Introduction to Web framework and DJango DJango
Template System
HTTP Client-Server Request – Response :
Basic Architecture :
The following diagram shows a very basic architecture of a web application and
depicts where HTTP sits:
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 :
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.
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
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:
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.
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()
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.
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.
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.
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:
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
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.
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',
#...
]
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:
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.
<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
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)
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 %}
I don't know.
{%endif%}
<p>
{% for day in days_of_week %}
{{day}}
</p>
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.
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.
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.
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()
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:
__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:
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:
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.
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';
(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:
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'
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)
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/
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).
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.
1. Click the Add button (next to Group) to create a new Group; enter
the Name "Library Members" for the group.
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:
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
class LoginForm(forms.Form):
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.
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()
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>
<br>
<br>
</center>
</div>
</form>
</body>
</html>
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.
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
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 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.
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".
class RenewBookModelForm(ModelForm):
def clean_due_back(self):
data = self.cleaned_data['due_back']
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).'),
}
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:
Django uses request and response objects to pass state through the system.
This document explains the APIs for HttpRequest and HttpResponse objects, which
are defined in the django.httpmodule.
HttpRequest objects
class HttpRequest[source]¶
Attributes¶
HttpRequest.scheme¶
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.
HttpRequest.path¶
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.
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()
do_something_else()
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.
Come inside views.py file that we created. And write the following code.
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:
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]¶
Methods¶
TemplateResponse.__init__(request, template, context=None, content_type=None, s
tatus=None, charset=None, using=None)[source]¶
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.
using
The NAME of a template engine to use for loading the template.
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.
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.")
def set_color(request):
if "favorite_color" in request.GET:
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.
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:
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.
There are a couple of simple rules for using Django’s sessions effectively:
For example, don’t use a session key called _fav_color , like this:
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 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!')
Because it’s a normal model, you can access sessions using the normal Django
database API:
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:
>>> s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
>>> s.get_decoded()
{'user_id': 42}
unittest.installHandler()
Install the control-c handler. When a signal.SIGINT is received all registered
results have TestResult.stop() called.
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
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
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
The easiest way to run all the tests is to use the command:
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.
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.
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:
Next, we will link the GitHub repository to Pipelines. Once linked, your application is
automatically built every time you make changes to the application.
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.
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.
In the next step, we add an environment for your application, and launch an EC2
instance to deploy the application to.
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:
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.
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.
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.