0% found this document useful (0 votes)
30 views

Python

The document discusses object-oriented programming concepts in Python including class, object, methods, inheritance, encapsulation, and polymorphism. It provides examples of creating classes and objects, defining methods, using inheritance to extend classes, encapsulating private attributes, and applying polymorphism through a common interface.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python

The document discusses object-oriented programming concepts in Python including class, object, methods, inheritance, encapsulation, and polymorphism. It provides examples of creating classes and objects, defining methods, using inheritance to extend classes, encapsulating private attributes, and applying polymorphism through a common interface.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

1

PROGRAMMING CONCEPTS

Introduction to OOPs in Python

Python is a multi-paradigm programming language. Meaning, it supports different


programming approach.

One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).

An object has two characteristics:

 attributes
 behavior

Let's take an example:

Parrot is an object,

 name, age, color are attributes


 singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

A process of using details from a new class without modifying existing


Inheritance
class.

Encapsulation Hiding the private details of a class from other objects.

A concept of using common operation in different ways for different


Polymorphism
data input.

Class

A class is a blueprint for the object.

We can think of class as an sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here,
parrot is an object.

The example for class of parrot can be :


2

class Parrot:

pass

Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.

Object

An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.

The example for object of parrot class can be:

obj = Parrot()

Here, obj is object of class Parrot.

Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.

Example 1: Creating Class and Object in Python


class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
Run

When we run the program, the output will be:


3

Blu is a bird

Woo is also a bird

Blu is 10 years old

Woo is 15 years old

In the above program, we create a class with name Parrot. Then, we define attributes. The
attributes are a characteristic of an object.

Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.

Then, we access the class attribute using __class __.species. Class attributes are same for all
instances of a class. Similarly, we access the instance attributes using blu.name and blu.age.
However, instance attributes are different for every instance of a class.

To learn more about classes and objects, go to Python Classes and Objects

Methods

Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.

Example 2 : Creating Methods in Python


class Parrot:

# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
4

When we run program, the output will be:

Blu sings 'Happy'

Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.

Inheritance

Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python


# parent class
class Bird:

def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Run

When we run this program, the output will be:


5

Bird is ready

Penguin is ready

Penguin

Swim faster

Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this
from swim()method. Again, the child class modified the behavior of parent class. We can see
this from whoisThis() method. Furthermore, we extend the functions of parent class, by
creating a new run() method.

Additionally, we use super() function before __init__() method. This is because we want to
pull the content of __init__() method from the parent class into the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation. In Python, we denote private attribute
using underscore as prefix i.e single “ _ “ or double “ __“.

Example 4: Data Encapsulation in Python


class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Run
6

When we run this program, the output will be:

Selling Price: 900

Selling Price: 900

Selling Price: 1000

In the above program, we defined a class Computer. We use __init__() method to store the
maximum selling price of computer. We tried to modify the price. However, we can’t change
it because Python treats the __maxprice as private attributes. To change the value, we used a
setter function i.e setMaxPrice() which takes price as parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).

Suppose, we need to color a shape, there are multiple shape option (rectangle, square, circle).
However we could use same method to color any shape. This concept is called
Polymorphism.

Example 5: Using Polymorphism in Python


class Parrot:
def fly(self):
print("Parrot can fly")

def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
7

# passing the object


flying_test(blu)
flying_test(peggy)
Run

When we run above program, the output will be:

Parrot can fly

Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
8

CHAPTER 3
PROGRAMMING CONCEPTS
Introduction to OOPs in Python

Python is a multi-paradigm programming language. Meaning, it supports different


programming approach.

One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).

An object has two characteristics:

 attributes
 behavior

Let's take an example:

Parrot is an object,

 name, age, color are attributes


 singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

A process of using details from a new class without modifying existing


Inheritance
class.

Encapsulation Hiding the private details of a class from other objects.

A concept of using common operation in different ways for different


Polymorphism
data input.

Class

A class is a blueprint for the object.

We can think of class as an sketch of a parrot with labels. It contains all the details about the
name, colors, size etc. Based on these descriptions, we can study about the parrot. Here,
parrot is an object.

The example for class of parrot can be :


9

class Parrot:

pass

Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.

Object

An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. Therefore, no memory or storage is allocated.

The example for object of parrot class can be:

obj = Parrot()

Here, obj is object of class Parrot.

Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.

Example 1: Creating Class and Object in Python


class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
Run

When we run the program, the output will be:


10

Blu is a bird

Woo is also a bird

Blu is 10 years old

Woo is 15 years old

In the above program, we create a class with name Parrot. Then, we define attributes. The
attributes are a characteristic of an object.

Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.

Then, we access the class attribute using __class __.species. Class attributes are same for all
instances of a class. Similarly, we access the instance attributes using blu.name and blu.age.
However, instance attributes are different for every instance of a class.

To learn more about classes and objects, go to Python Classes and Objects

Methods

Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.

Example 2 : Creating Methods in Python


class Parrot:

# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
11

When we run program, the output will be:

Blu sings 'Happy'

Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.

Inheritance

Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python


# parent class
class Bird:

def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Run

When we run this program, the output will be:


12

Bird is ready

Penguin is ready

Penguin

Swim faster

Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this
from swim()method. Again, the child class modified the behavior of parent class. We can see
this from whoisThis() method. Furthermore, we extend the functions of parent class, by
creating a new run() method.

Additionally, we use super() function before __init__() method. This is because we want to
pull the content of __init__() method from the parent class into the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation. In Python, we denote private attribute
using underscore as prefix i.e single “ _ “ or double “ __“.

Example 4: Data Encapsulation in Python


class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Run
13

When we run this program, the output will be:

Selling Price: 900

Selling Price: 900

Selling Price: 1000

In the above program, we defined a class Computer. We use __init__() method to store the
maximum selling price of computer. We tried to modify the price. However, we can’t change
it because Python treats the __maxprice as private attributes. To change the value, we used a
setter function i.e setMaxPrice() which takes price as parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).

Suppose, we need to color a shape, there are multiple shape option (rectangle, square, circle).
However we could use same method to color any shape. This concept is called
Polymorphism.

Example 5: Using Polymorphism in Python


class Parrot:
def fly(self):
print("Parrot can fly")

def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
14

# passing the object


flying_test(blu)
flying_test(peggy)
Run

When we run above program, the output will be:

Parrot can fly

Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
15

PYTHON MYSQL

Select

import PyMySQL

# Open database connection

db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.

sql = "SELECT * FROM EMPLOYEE \

WHERE INCOME > '%d'" % (1000)

try:

# Execute the SQL command

cursor.execute(sql)
16

# Fetch all the rows in a list of lists.

results = cursor.fetchall()

for row in results:

fname = row[0]

lname = row[1]

age = row[2]

sex = row[3]

income = row[4]

# Now print fetched result

print ("fname = %s,lname = %s,age = %d,sex = %s,income = %d" % \

(fname, lname, age, sex, income ))

except:

print ("Error: unable to fetch data")

# disconnect from server

import pymysql.cursors

# Connect to the database.


connection = pymysql.connect(host='192.168.5.134',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

print ("connect successful!!")

try:

with connection.cursor() as cursor:

# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "

# Execute query.
17

cursor.execute(sql)

print ("cursor.description: ", cursor.description)

print()

for row in cursor:


print(row)

finally:
# Close connection.
connection.close()

insert

import PyMySQL

# Open database connection

db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.

sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \

LAST_NAME, AGE, SEX, INCOME) \

VALUES ('%s', '%s', '%d', '%c', '%d' )" % \

('Mac', 'Mohan', 20, 'M', 2000)

try:

# Execute the SQL command

cursor.execute(sql)

# Commit your changes in the database


18

db.commit()

except:

# Rollback in case there is any error

db.rollback()

# disconnect from server

db.close()

# Use your utility module.


import myconnutils
import pymysql.cursors

connection = myconnutils.getConnection()

print ("Connect successful!")

try :
cursor = connection.cursor()

sql = "Select max(Grade) as Max_Grade from Salary_Grade "


cursor.execute(sql)

# 1 row.
oneRow = cursor.fetchone()

# Output: {'Max_Grade': 4} or {'Max_Grade': None}


print ("Row Result: ", oneRow)

grade = 1

if oneRow != None and oneRow["Max_Grade"] != None:


19

grade = oneRow["Max_Grade"] + 1

cursor = connection.cursor()

sql = "Insert into Salary_Grade (Grade, High_Salary, Low_Salary) " \


+ " values (%s, %s, %s) "

print ("Insert Grade: ", grade)

# Execute sql, and pass 3 parameters.


cursor.execute(sql, (grade, 2000, 1000 ) )

connection.commit()

finally:
connection.close()

update

import PyMySQL

# Open database connection

db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to UPDATE required records

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1

WHERE SEX = '%c'" % ('M')

try:

# Execute the SQL command


20

cursor.execute(sql)

# Commit your changes in the database

db.commit()

except:

# Rollback in case there is any error

db.rollback()

# disconnect from server

db.close()

import myconnutils
import pymysql.cursors
import datetime

connection = myconnutils.getConnection()

print ("Connect successful!")

try :
cursor = connection.cursor()

sql = "Update Employee set Salary = %s, Hire_Date = %s where Emp_Id = %s "

# Hire_Date
newHireDate = datetime.date(2002, 10, 11)

# Execute sql, and pass 3 parameters.


rowCount = cursor.execute(sql, (850, newHireDate, 7369 ) )

connection.commit()

print ("Updated! ", rowCount, " rows")

finally:
# Close connection.
21

Delete

import PyMySQL

# Open database connection

db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method

cursor = db.cursor()

# Prepare SQL query to DELETE required records

sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)

try:

# Execute the SQL command

cursor.execute(sql)

# Commit your changes in the database

db.commit()

except:

# Rollback in case there is any error

db.rollback()

# disconnect from server

db.close()
22

# Use your utility module.


import myconnutils

connection = myconnutils.getConnection()

print ("Connect successful!")

try :
cursor = connection.cursor()

sql = "Delete from Salary_Grade where Grade = %s"

# Execute sql, and pass 1 parameters.


rowCount = cursor.execute(sql, ( 3 ) )

connection.commit()

print ("Deleted! ", rowCount, " rows")

finally:
# Close connection.
connection.close()
23

Python mail

https://myaccount.google.com/lesssecureapps

import smtplib

# list of email_id to send the mail

li = ["[email protected]"]

for i in range(len(li)):

s = smtplib.SMTP('smtp.gmail.com', 587)

s.starttls()

s.login("[email protected]", "******")

message = "test message..............."

s.sendmail("[email protected]", li[i], message)

s.quit()

Performing Google Search using Python code


Installation
google package has one dependency on beautifulsoup which need to be installed first.
pip install beautifulsoup4
Then install google package
pip install google
Required Function and its parameters
24

search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0)


 query : query string that we want to search for.
 tld : tld stands for top level domain which means we want to search our result on
google.com or google.in or some other domain.
 lang : lang stands for language.
 num : Number of results we want.
 start : First result to retrieve.
 stop : Last result to retrieve. Use None to keep searching forever.
 pause : Lapse to wait between HTTP requests. Lapse too short may cause Google to block
your IP. Keeping significant lapse will make your program slow but its safe and better
option.
 Return : Generator (iterator) that yields found URLs. If the stop parameter is None the
iterator will loop forever.
Python codes on how to do google search using python script

Example1: google_search.py
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")

# to search
query = "n"

for j in search(query, tld="co.in", num=10, stop=1, pause=2):


print(j)
Run on IDE
Output:

Implementing Web Scraping in Python with BeautifulSoup


There are mainly two ways to extract data from a website:
25

 Use the API of the website (if it exists). For example, Facebook has the Facebook Graph
API which allows retrieval of data posted on Facebook.
 Access the HTML of the webpage and extract useful information/data from it. This
technique is called web scraping or web harvesting or web data extraction.
pip install requests
pip install html5lib
pip install bs4
Step 2: Accessing the HTML content from webpag

et us try to understand this piece of code.


 First of all import the requests library.
 Then, specify the URL of the webpage you want to scrape.
 Send a HTTP request to the specified URL and save the response from server in a response
object called r.
 Now, as print r.content to get the raw HTML content of the webpage. It is of ‘string’ type.
Step 3: Parsing the HTML content
#This will not run on online IDE

import requests
from bs4 import BeautifulSoup

URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)

soup = BeautifulSoup(r.content, 'html5lib')


print(soup.prettify())

Working with zip files in Python


# importing required modules
from zipfile import ZipFile

# specifying the zip file name


file_name = "my_python_files.zip"

# opening the zip file in READ mode


with ZipFile(file_name, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()

# extracting all the files


26

print('Extracting all the files now...')


zip.extractall()
print('Done!')

2. Writing to a zip file

from zipfile import ZipFile

import os

def get_all_file_paths(directory):

# initializing empty file paths list

file_paths = []

# crawling through directory and subdirectories

for root, directories, files in os.walk(directory):

for filename in files:

# join the two strings in order to form the full filepath.

filepath = os.path.join(root, filename)

file_paths.append(filepath)

# returning all file paths

return file_paths

def main():
27

# path to folder which needs to be zipped

directory = 'folder'

# calling function to get all file paths in the directory

file_paths = get_all_file_paths(directory)

# printing the list of all files to be zipped

print('Following files will be zipped:')

for file_name in file_paths:

print(file_name)

# writing files to a zipfile

with ZipFile('my_python_files.zip','w') as zip:

# writing each file one by one

for file in file_paths:

zip.write(file)

print('All files zipped successfully!')

if __name__ == "__main__":

main()

3. Getting all information about a zip file

rom zipfile import ZipFile


import datetime
28

# specifying the zip file name


file_name = "example.zip"

# opening the zip file in READ mode


with ZipFile(file_name, 'r') as zip:
for info in zip.infolist():
print(info.filename)
print('\tModified:\t' + str(datetime.datetime(*info.date_time)))
print('\tSystem:\t\t' + str(info.create_system) + '(0 = Windows, 3 = Unix)')
print('\tZIP version:\t' + str(info.create_version))
print('\tCompressed:\t' + str(info.compress_size) + ' bytes')
print('\tUncompressed:\t' + str(info.file_size) + ' bytes')
29

Django
Introduction

Django is a web application framework written in Python programming language.


It is a MVT (Model View Template) based framework. The concept behind to build
Django was to develop a framework that can meet fast-moving newsroom deadlines
while satisfying the tough requirements of clients.

This framework uses a famous tag line:The web framework for perfectionists
with deadlines.

History

Django was design and developed by Lawrence journal world in 2003 and publicly
released under BSD license in July 2005. Currently, DSF (Django Software
Foundation) maintains it?s development and release cycle.

Django initially released on 21, July 2005 and current stable version is 2.0.3 which
was released on 6 March, 2018.

Django Version History

Version Date Date


0.90 16 Nov 2005
0.91 11 Jan 2006 magic removal
0.96 23 Mar 2007 newforms, testing tools
1.0 3 Sep 2008 API stability, decoupled admin, unicode
1.1 29 Jul 2009 Aggregates, transaction based tests
1.2 17 May 2010 Multiple db connections, CSRF, model validation
1.3 23 Mar 2011 Timezones, in browser testing, app templates.
1.5 26 Feb 2013 Python 3 Support, configurable user model
Dedicated to Malcolm Tredinnick, db transaction
1.6 6 Nov 2013
management, connection pooling.
Migrations, application loading and
1.7 2 Sep 2014
configuration.
Migrations, application loading and
1.8 LTS 2 Sep 2014
configuration.
Native support for multiple template
1.8 LTS 1 Apr 2015
engines.Supported until at least April 2018
Automatic password validation. New styling for
1.9 1 Dec 2015
admin interface.
Full text search for PostgreSQL. New-style
1.10 1 Aug 2016
middleware.
30

1.11 Last version to support Python 2.7.Supported


1.11 LTS
LTS until at least April 2020
First Python 3-only release, Simplified URL
2.0 Dec 2017
routing syntax, Mobile friendly admin.

Popularity

Django is widely accepted and used by various well-known sites such as:

 Instagram
 Mozilla
 Disqus
 Pinterest
 Bitbucket
 The Washington Times

Features of Django

 Rapid Development
 Secure
 Scalable
 Fully loaded
 Versatile
 Open Source
 Vast and Supported Community

DJANGO- INSTALLATION
31

Installation

The first thing we need to do is install some programs on our machine so to be able
to start playing with Django. The basic setup consists of installing Python,
Virtualenv, and Django.

Installing Python 3.6.2

Pick the right version accordingly to your Windows distribution. If you are not sure
which one is the right for you, the chances are you want to download the Windows
x86-64 executable installer version.

Go to your Downloads directory, right click on the installer and click on Run as
administrator.
32

Make sure you check the option Add Python 3.6 to PATH and click on the Install
Now option.

After the installation completes, you should see the following screen:
33

Now search for the Command Prompt program and open it:

To test if everything is working fine so far, type following command:

python --version

As an output you should see:

Python 3.6.2
34

Installing Virtualenv

In the Command Prompt, execute the command below:

pip install virtualenv


mkdir myproject
cd myproject

This folder is the higher level directory that will store all the files and things related
to our Django project, including its virtual environment.

So let’s start by creating our very first virtual environment and installing Django.

Inside the myproject folder:

virtualenv venv
35

Our virtual environment is created. Now before we start using it, we need to
activate:

venv\Scripts\activate

You will know it worked if you see (venv) in front of the command line, like this:

venv\Scripts\deactivate.bat

But let’s keep it activated for the next steps.

Installing Django 1.11.4

It’s very straightforward. Now that we have the venv activated, run the following
command to install Django:

pip install django


36

We are all set up now!

Starting a New Project

To start a new Django project, run the command below:

django-admin startproject myproject

The command-line utility django-admin is automatically installed with Django.

After we run the command above, it will generate the base folder structure for a
Django project.

Right now, our myproject directory looks like this:

myproject/ <-- higher level folder


|-- myproject/ <-- django project folder
| |-- myproject/
| | |-- __init__.py
| | |-- settings.py
| | |-- urls.py
| | |-- wsgi.py
| +-- manage.py
+-- venv/ <-- virtual environment folder

Our initial project structure is composed of five files:


37

manage.py: a shortcut to use the django-admin command-line utility. It’s used to


run management commands related to our project. We will use it to run the
development server, run tests, create migrations and much more.

__init__.py: this empty file tells Python that this folder is a Python package.

settings.py: this file contains all the project’s configuration. We will refer to this
file all the time!

urls.py: this file is responsible for mapping the routes and paths in our project. For
example, if you want to show something in the URL /about/, you have to map it
here first.

wsgi.py: this file is a simple gateway interface used for deployment. You don’t have
to bother about it. Just let it be for now.

Executing the command:

python manage.py runserver

For now, you can ignore the migration errors; we will get to that later.

Now open the following URL in a Web browser: http://127.0.0.1:8000 and you
should see the following page:
38

Hit CTRL + BREAK to stop the development server.

Django Apps

In the Django philosophy we have two important concepts:

app: is a Web application that does something. An app usually is composed of a set
of models (database tables), views, templates, tests.

project: is a collection of configurations and apps. One project can be composed of


multiple apps, or a single app.

Alright! So, to illustrate let’s create a simple Web Forum or Discussion Board. To
create our first app, go to the directory where the manage.py file is and executes
the following command:

django-admin startapp boards

Notice that we used the command startapp this time.

This will give us the following directory structure:

myproject/
|-- myproject/
| |-- boards/ <-- our new django app!
| | |-- migrations/
| | | +-- __init__.py
| | |-- __init__.py
| | |-- admin.py
| | |-- apps.py
| | |-- models.py
| | |-- tests.py
| | +-- views.py
| |-- myproject/
| | |-- __init__.py
| | |-- settings.py
39

| | |-- urls.py
| | |-- wsgi.py
| +-- manage.py
+-- venv/

So, let’s first explore what each file does:

migrations/: here Django store some files to keep track of the changes you create
in the models.py file, so to keep the database and the models.py synchronized.

admin.py: this is a configuration file for a built-in Django app called Django
Admin.

apps.py: this is a configuration file of the app itself.

models.py: here is where we define the entities of our Web application. The models
are translated automatically by Django into database tables.

tests.py: this file is used to write unit tests for the app.

views.py: this is the file where we handle the request/response cycle of our Web
application.

Now that we created our first app, let’s configure our project to use it.

To do that, open the settings.py and try to find the INSTALLED_APPS variable:

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

As you can see, Django already come with 6 built-in apps installed. They offer
common functionalities that most Web applications need, like authentication,
sessions, static files management (images, javascripts, css, etc.) and so on.

We will explore those apps as we progress in this tutorial series. But for now, let
them be and just add our boards app to the list of INSTALLED_APPS:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
40

'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'boards',
]

Using the analogy of the square and circles from the previous comic, the yellow
circle would be our boards app, and the django.contrib.admin,
django.contrib.auth, etc, would be the red circles.

Hello, World!Let’s write our first view. We will explore it in great detail in the
next tutorial. But for now, let’s just experiment how it looks like to create a new
page with Django.

Open the views.py file inside the boards app, and add the following code:

views.py

from django.http import HttpResponse

def home(request):
return HttpResponse('Hello, World!')

Views are Python functions that receive an HttpRequest object and returns an
HttpResponse object. Receive a request as a parameter and returns a response as a
result. That’s the flow you have to keep in mind!

So, here we defined a simple view called home which simply returns a message
saying Hello, World!.

Now we have to tell Django when to serve this view. It’s done inside the urls.py
file:

urls.py

from django.conf.urls import url


from django.contrib import admin

from boards import views

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
41

If you compare the snippet above with your urls.py file, you will notice I added the
following new line: url(r'^$', views.home, name='home') and imported the views
module from our app boards using from boards import views.

As I mentioned before, we will explore those concepts in great detail later on.

But for now, Django works with regex to match the requested URL. For our home
view, I’m using the ^$ regex, which will match an empty path, which is the
homepage (this url: http://127.0.0.1:8000). If I wanted to match the URL
http://127.0.0.1:8000/homepage/, my url would be: url(r'^homepage/$',
views.home, name='home').

Let’s see what happen:

python manage.py runserver

In a Web browser, open the http://127.0.0.1:8000 URL:

Django App

Creating an App

python manage.py startapp appname


42

views.py

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse

def hello(request):

return HttpResponse("<h2>Hello, Welcome to Django!</h2>")

urls.py

from django.contrib import admin

from django.urls import path

from myapp import views

urlpatterns = [

path('admin/', admin.site.urls),

path('hello/', views.hello),

localhost:8000/hello
43

Django MVT

MVT (Model View Template) is a software design pattern which is a collection of


three parts Model View and Template. The Model helps to handle database. It is a
data access layer that handles the data.

The Template is a presentation layer that handles all the User Interface part. The
View is used to execute the business logic and interact with model to carry data and
renders template.

Django Admin Interface

The admin app (django.contrib.admin) is enabled by default and already added


into INSTALLED_APPS section of settings file.

To access it at browser use '/admin/' at local machine like:

localhost:8000/admin/ and it shows the following output:

>>> import django


>>> print(django.get_version())
2.0
44

Create an Admin User

python3 managen.py createsuperuser

python3 manage.py runserver


45

Django Session

A session is a mechanism to store information on the server side during the


interaction with the web application.

In Django, by default session stores in the database and also allows file-based and
cache based sessions. It is implemented via a piece of middleware and can be
enabled by using the following code.

Put django.contrib.sessions.middleware.SessionMiddleware in
MIDDLEWARE and django.contrib.sessions in INSTALLED_APPS of
settings.py file.

To set and get the session in views, we can use request.session and can set multiple
times too.

The class backends.base.SessionBase is a base class of all session objects. It


contains the following standard methods.

Method Description

__getitem__(key) It is used to get session value.

__setitem__(key, It is used to set session value.


value)

__delitem__(key) It is used to delete session object.

__contains__(key) It checks whether the container contains the particular


session object or not.

get(key, It is used to get session value of the specified key.


default=None)

Let's see an example in which we will set and get session values. Two functions are
defined in the views.py file.

Django Session Example

The first function is used to set and the second is used to get session values.

//views.py

from django.shortcuts import render


from django.http import HttpResponse
46

def setsession(request):
request.session['sname'] = 'irfan'
request.session['semail'] = '[email protected]'
return HttpResponse("session is set")
def getsession(request):
studentname = request.session['sname']
studentemail = request.session['semail']
return HttpResponse(studentname+" "+studentemail);

Url mapping to call both the functions.

// urls.py

from django.contrib import admin


from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('ssession',views.setsession),
path('gsession',views.getsession)
]

Run Server

$ python3 manage.py runserver

And set the session by using localhost:8000/ssession

The session has been set, to check it, use localhost:8000/gsession


47

Django Mail Setup

Sending email using Django is pretty easy and require less configuration. In this
tutorial, we will send email to provided email.

For this purpose, we will use Google's SMTP and a Gmail account to set sender.

Django provides built-in mail library django.core.mail to send email.

Before sending email, we need to make some changes in Gmail account because for
security reasons Google does not allow direct access (login) by any application. So,
login to the Gmail account and follow the urls. It will redirect to the Gmail account
settings where we need to allow less secure apps but toggle the button. See the
below screenshot.

https://myaccount.google.com/lesssecureapps

After that follow this url that is a additional security check to verify the make
security constraint.
48

https://accounts.google.com/DisplayUnlockCaptcha

Click on continue and all is setup.

Django Configuration

Provide the smtp and Gmail account details into the settings.py file. For example

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '*********'

Import Mail Library

from django.core.mail import send_mail

Now, write a view function that uses built-in mail function to send mail. See the
example

Django Email Example

This example contains the following files.

// views.py

from django.http import HttpResponse


from djangpapp import settings
from django.core.mail import send_mail

def mail(request):
subject = "Greetings"
msg = "Congratulations for your success"
49

to = "[email protected]"
res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to])
if(res == 1):
msg = "Mail Sent Successfuly"
else:
msg = "Mail could not sent"
return HttpResponse(msg)

// urls.py

Put following url into urls.py file.

path('mail',views.mail)

Run Server and access it at browser, see the output.

Here, the both email ids are mine, so I can verify the email by login to the account.

And after login, here we go!! I got the mail.

Django, MySQL for Windows

Personally i prefer Postgres for my applications, however like all things some poeple
prefer others such as MySQL, MSSQL or even MongoDB.
50

To get started we need to confirm what version of Python you are running this can
be achieved by opening a command prompt and entering the following:

python --version

Mine is currently Python 3.6.3, this tutorial should work the same if you are using a
different version of Python however, the same results cannot be guaranteed.

We need a Virtualenv
As with any project we should always use a virtual environment, this allows us to
isolate the packages we have from our global Python install.

Lets get started by making sure we have one setup. But first we need to install
virtualenv if we dont already.

pip install virtualenv

Now we need a place to store them for my projects i do the following structure:

Folder Structure

We need to activate it now, we do so by entering the following for Windows:

\path\to\your\virtualenv\Scripts\activate

We can confirm it is active by seeing (virtualenvname) before the CMD prompt, like
so:
51

Django, Mysql

The missing step here would be to ensure you have MySQL server installed on your
local machine aswell if you intend to develop on a local database initially. For this
example i will be connecting to a remote MySQL database.

We can now install Django and any other packages we want, for this example we
will just get MySQL.

pip install django mysqlclient

This will download and install the packages. We will now setup our test application
and store the files in the app folder.

django-admin.py startproject awesomeapp

We can now build our DATABASES settings in our settings.py as follows, i will
using VS Code to edit.

DATABASES updated for Mysql

To check it is working we will simply make migrations and migrate

python manage.py makemigrations


python manage.py migrate
52

Django Database Connectivity

The settings.py file contains all the project settings along with database connection
details. By default, Django works with SQLite, database and allows configuring for
other databases as well.

Database connectivity requires all the connection details such as database name,
user credentials, hostname drive name etc.

To connect with MySQL, django.db.backends.mysql driver is used to establishing


a connection between application and database. Let's see an example.

We need to provide all connection details in the settings file. The settings.py file of
our project contains the following code for the database.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangoApp',
'USER':'root',
'PASSWORD':'mysql',
'HOST':'localhost',
'PORT':'3306'
}
}

Migration is a way of applying changes that we have made to a model, into the
database schema. Django creates a migration file inside the migration folder for
each model to create the table schema, and each table is mapped to the model of
which migration is created.
53

Django provides the various commands that are used to perform migration related
tasks. After creating a model, we can use these commands.

makemigrations : It is used to create a migration file that contains code for the
tabled schema of a model.

migrate : It creates table according to the schema defined in the migration file.

sqlmigrate : It is used to show a raw SQL query of the applied migration.

showmigrations : It lists out all the migrations and their status.

After providing details, check the connection using the migrate command.

$ python manage.py migrate

Migrating Model

Well, till here, we have learned to connect Django application to the MySQL
database. Next, we will see how to create a table using the model.

Each Django's model is mapped to a table in the database. So after creating a model,
we need to migrate it. Let's see an example.

Suppose, we have a model class Employee in the models.py file that contains the
following code.

// models.py

from django.db import models


class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=100)
54

econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"

Django first creates a migration file that contains the details of table structure. To
create migration use the following command.

Python manage.py makemigrations

The created migration file is located into migrations folder and contains the
following code.

from django.db import migrations, models


class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=F
alse, verbose_name='ID')),
('eid', models.CharField(max_length=20)),
('ename', models.CharField(max_length=100)),
('econtact', models.CharField(max_length=15)),
],
options={
'db_table': 'employee',
},
),
]

Now, migrate to reflect the changes into the database.


55

Python manage.py migrate

Building a CRUD application using Python and Django

Before we start writing applications, we must know a little about what is Django.
Django is a web application framework that acts more of an MTV pattern instead of
MVC. Think it this way:

 Model remains model

 View has been replaced by Templates

 Controller gets replaced by View

A simple Hello-world application is just a few lines of code in Django! But moving
from this simple thing a full fledged application can be a daunting task in itself. There
are other concepts that can help proceed further such as ORM, migrations etc that help
in building a bigger application. But for this we’ll be building a simple CRUD( Create,
Retrieve, Update and Delete ) application.

To get started with you need to have python and virtualenv installed on your machine.
Python is already installed on the linux systems. But you'll need to install virtualenv.
To install virtualenv follow the command:
56

sudo apt-get install python-pip


sudo pip install virtualenv
Application Structure

Before we actually start writing code we need to get a hold of the application structure.
We'll first execute several commands that are essential in django project development.

After installing virtualenv, we need to set the environment up.

virtualenv venv

We are setting a virtual environment of the name venv here. Now we need to activate
it.
source venv/bin/activate
cd venv

Now that it has been activated. We need to start our project. Feed in the following
command to start a project.
pip install django==1.11.8
mkdir app && cd app
django-admin startproject crudapp
view rawinstallation.md

The first line installs Django v1.11.8 and creates a directory named app in the parent
directory. the third line starts a project named crudapp in the app directory. The
directory tree should look like
app
└── crudapp
├── crudapp
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py

We'll see the meaning of each file and what it does one by one. But first, to test if you
are going in the right directoion, run the following command.
57

python manage.py runserver

If you get an output like below then you're doing it right.

Let's see what exactly the different files that we created mean.
 __init__.py : Acts as an entry point for your python project.
 settings.py : Describes the configuration of your Django installation and lets
Django know which settings are available.
 urls.py : used to route and map URLs to their views.
 wsgi.py : contains the configuration for the Web Server Gateway Interface. The
Web Server Gateway Interface (WSGI) is the Python platform standard for the
deployment of web servers and applications.
Writing the Application

Now this is where we start coding our app. For this operation we'll consider blog post
as our entity. We'll be applying CRUD operations to blog posts.

The app in our project will be called blog_posts.

python manage.py startapp blog_posts

This will create the necessary files that we require.

First and foremost create the Model of our application.


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
58

from django.db import models

# Create your models here.


class blog_posts(models.Model):
title = models.CharField(max_length=400)
tag = models.CharField(max_length=50)
author = models.CharField(max_length=120)

def __unicode__(self):
return self.title

def get_post_url(self):
return reverse('post_edit', kwargs={'pk': self.pk})

Now that we have our model ready, we'll need to migrate it to the database.
python manage.py makemigrations
python manage.py migrate

Now we create our Views where we define each of our CRUD definition.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, redirect, get_object_or_404


from django.forms import ModelForm

from blog_posts.models import blog_posts


# Create your views here.

class PostsForm(ModelForm):
class Meta:
model = blog_posts
fields = ['id', 'title', 'author']

def post_list(request, template_name='blog_posts/post_list.html'):


posts = blog_posts.objects.all()
data = {}
data['object_list'] = posts
return render(request, template_name, data)

def post_create(request, template_name='blog_posts/post_form.html'):


form = PostsForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('blog_posts:post_list')
return render(request, template_name, {'form': form})
59

def post_update(request, pk, template_name='blog_posts/post_form.html'):


post = get_object_or_404(blog_posts, pk=pk)
form = PostsForm(request.POST or None, instance=post)
if form.is_valid():
form.save()
return redirect('blog_posts:post_list')
return render(request, template_name, {'form': form})

def post_delete(request, pk, template_name='blog_posts/post_delete.html'):


post = get_object_or_404(blog_posts, pk=pk)
if request.method=='POST':
post.delete()
return redirect('blog_posts:post_list')
return render(request, template_name, {'object': post})
Now that we have our Views, we create mappings to URL in
our /crudapp/blog_posts/urls.py file. Make a note that the following is our app specific
mappings.

"""
crudapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from django.conf.urls import url
from django.contrib import admin
from blog_posts import views

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.post_list, name='post_list'),
url(r'^new$', views.post_create, name='post_new'),
url(r'^edit/(?P<pk>\d+)$', views.post_update, name='post_edit'),
url(r'^delete/(?P<pk>\d+)$', views.post_delete, name='post_delete'),
]
Now we create project specific mappings in /crudapp/crudapp/urls.py.
"""
Crudapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from django.conf.urls import url, include
from django.contrib import admin
from crudapp.views import home

urlpatterns = [
url(r'^admin/', admin.site.urls),
60

url(r'^blog_posts/', include('blog_posts.urls', namespace='blog_posts')),


url(r'^$', home, name='home' ),
]

Now almost everything is done and all we need to do is create our templates to test the
operations.
Go ahead and create a templates/blog_posts directory in crudapp/blog_posts/.
 templates/blog_posts/post_list.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
beta.2/css/bootstrap.min.css">
<title>Django CRUD application!</title>
</head>
<body>
<div class="container">
<h1>Blog Post List!</h1>
<ul>
{% for post in object_list %}
<li><p>Post ID: <a href="{% url "blog_posts:post_edit" post.id %}">{{
post.id }}</a></p>
<p>Title: {{ post.title }}</p>
<a href="{% url "blog_posts:post_delete" post.id %}">Delete</a>
</li>
{% endfor %}
</ul>

<a href="{% url "blog_posts:post_new" %}">New Blog post entry</a>


</div>
</body>
</html>
 templates/blog_posts/post_form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
beta.2/css/bootstrap.min.css">
<title>Django CRUD application!</title>
</head>
<body>
<div class="container">
61

<form method="post">{% csrf_token %}


{{ form.as_p }}
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
</div>
</body>
</html>
 templates/blog_posts/post_delete.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
beta.2/css/bootstrap.min.css">
<title>Django CRUD application!</title>
</head>
<body>
<div class="container">
<form method="post">{% csrf_token %}
Are you sure you want to delete "{{ object }}" ?
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
</div>
</body>
</html>

Now we have all the necessary files and code that we require.

The final project tree should look like following:


crudapp
├── blog_posts
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ ├── models.py
│ ├── templates
│ │ └── blog_posts
│ │ ├── post_delete.html
│ │ ├── post_form.html
│ │ └── post_list.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
├── crudapp
│ ├── __init__.py
62

│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── db.sqlite3
├── manage.py
└── requirements.txt

Execute python manage.py runserver and voila!! You have your Django app ready.

You might also like