[go: up one dir, main page]

0% found this document useful (0 votes)
9 views39 pages

20CSC21Notes 4

The document provides an overview of web programming in Python, focusing on basic concepts such as arrays and classes. It explains how to create, manipulate, and access arrays using the array module, as well as the principles of object-oriented programming, including class instantiation, methods, and the use of interfaces. Additionally, it touches on Python's HTTP package for working with the HyperText Transfer Protocol.

Uploaded by

songoku77801
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views39 pages

20CSC21Notes 4

The document provides an overview of web programming in Python, focusing on basic concepts such as arrays and classes. It explains how to create, manipulate, and access arrays using the array module, as well as the principles of object-oriented programming, including class instantiation, methods, and the use of interfaces. Additionally, it touches on Python's HTTP package for working with the HyperText Transfer Protocol.

Uploaded by

songoku77801
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Web Programming in python :

Basic Concepts :
Arrays :
An array is a collection of items stored at contiguous memory
locations. The idea is to store multiple items of the same type
together.
This makes it easier to calculate the position of each element by
simply adding an offset to a base value,
The memory location of the first element of the
array (generally denoted by the name of the
array).
For simplicity, we can think of an array a fleet of stairs where on
each step is placed a value (let’s say one of your friends). Here,
you can identify the location of any of your friends by simply
knowing the count of the step they are on. Array can be handled
in Python by a module named array. They can be useful when we
have to manipulate only a specific data type values. A user can
treat lists as arrays. However, user cannot constraint the type of
elements stored in a list. If you create arrays using
the array module, all elements of the array must be of the same
type.
Creating an Array:-
Array in Python can be created by importing array module. array
(data_type, value_list) is used to create an array with data type and value
list specified in its arguments.
# Python program to demonstrate
# Creation of Array

# importing "array" for array creations


import array as arr

# creating an array with integer type


a = arr.array('i', [1, 2, 3])

# printing original array


print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()

# creating an array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array


print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")

Adding Elements to an Array:-

Elements can be added to the Array by using built-in insert () function.


Insert is used to insert one or more data elements into an array. Based on
the requirement, a new element can be added at the beginning, end, or any
given index of array. append () is also used to add the value mentioned in
its arguments at the end of the array.
# Python program to demonstrate
# Adding Elements to a Array

# importing "array" for array creations


import array as arr

# array with int type


a = arr.array('i', [1, 2, 3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3):
print (a[i], end =" ")
print()

# inserting array using


# insert() function
a.insert(1, 4)

print ("Array after insertion : ", end =" ")


for i in (a):
print (i, end =" ")
print()

# array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3):
print (b[i], end =" ")
print()

# adding an element using append()


b.append(4.4)
print ("Array after insertion : ", end =" ")
for i in (b):
print (i, end =" ")
print()

Accessing elements from the Array:-

In order to access the array items refer to the index number. Use the index
operator [ ] to access an item in an array. The index must be an integer.

# Python program to demonstrate


# accessing of element from list

# importing array module


import array as arr

# array with int type


a = arr.array('i', [1, 2, 3, 4, 5, 6])

# accessing element of array


print("Access element is: ", a[0])

# accessing element of array


print("Access element is: ", a[3])

# array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

# accessing element of array


print("Access element is: ", b[1])

# accessing element of array


print("Access element is: ", b[2])
Removing Elements from the Array:-

Elements can be removed from the array by using built-in remove ()


function but an Error arises if element doesn’t exist in the set. Remove ()
method only removes one element at a time, to remove range of elements,
iterator is used. pop() function can also be used to remove and return an
element from the array, but by default it removes only the last element of
the array, to remove element from a specific position of the array, index of
the element is passed as an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the
searched element.
# Python program to demonstrate
# Removal of elements in a Array

# importing "array" for array operations


import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 5])

# printing original array


print ("The new created array is : ", end ="")
for i in range (0, 5):
print (arr[i], end =" ")

print ("\r")

# using pop() to remove element at 2nd position


print ("The popped element is : ", end ="")
print (arr.pop(2))

# printing array after popping


print ("The array after popping is : ", end ="")
for i in range (0, 4):
print (arr[i], end =" ")

print("\r")

# using remove() to remove 1st occurrence of 1


arr.remove(1)

# printing array after removing


print ("The array after removing is : ", end ="")
for i in range (0, 3):
print (arr[i], end =" ")

Slicing of an Array:-

In Python array, there are multiple ways to print the whole array with all
the elements, but to print a specific range of elements from the array, we
use Slice operation. Slice operation is performed on array with the use of
colon (:). To print elements from beginning to a range use [: Index], to print
elements from end use [:-Index], to print elements from specific Index till
the end use [Index:], to print elements within a range, use [Start Index: End
Index] and to print whole List with the use of slicing operation, use [:].
Further, to print whole array in reverse order, use [::-1].
Classes :

An Object is an instance of a Class. A class is like a blueprint while an


instance is a copy of the class with actual values. Python is object
oriented programming language which stress on objects i.e. it mainly
emphasize on functions. Objects are basically an encapsulation of
data variables and methods acting on that data into a single entity.
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values. It’s not an idea
anymore, it’s an actual dog, like a dog of breed pug who’s seven years
old. You can have many dogs to create many different instances, but
without the class as a guide, you would be lost, not knowing what
information is required.
An object consists of:
State: It is represented by the attributes of an object. It also reflects
the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
Identity: It gives a unique name to an object and enables one object
to interact with other objects.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class.
But the values of those attributes, i.e. the state are unique for each
object. A single class may have any number of instances.

Declaring an object –
# Python3 program to
# demonstrate instantiating
# a class
class Dog:

# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()

The self :

Class methods must have an extra first parameter in the method


definition. We do not give a value for this parameter when we call the
method, Python provides it.
If we have a method that takes no arguments, then we still have to
have one argument.
This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method (arg1,
arg2), this is automatically converted by Python into MyClass.method
(myobject, arg1, arg2) – this is all the special self is about.

__init__ method

The init method is similar to constructors in C++ and Java.


Constructors are used to initializing the object’s state. Like methods,
a constructor also contains a collection of statements (i.e.
instructions) that are executed at the time of Object creation. It runs
as soon as an object of a class is instantiated. The method is useful to
do any initialization you want to do with your object.

# A Sample class with init method


class Person:

# init method or constructor


def init (self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

Class and Instance Variables

Instance variables are for data, unique to each instance and class
variables are for attributes and methods shared by all instances of the
class. Instance variables are variables whose value is assigned inside
a constructor or method with self whereas class variables are
variables whose value is assigned in the class.

Defining instance variable using a constructor.


# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Dog


class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def init (self, breed, color):
# Instance Variable
self.breed = breed
self.color = color

# Objects of Dog class


Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)

print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

Defining instance variable using the normal method.

# Python3 program to show that we can create


# instance variables inside methods

# Class for Dog


class Dog:
# Class Variable
animal = 'dog'

# The init method or constructor


def init (self, breed):

# Instance Variable
self.breed = breed

# Adds an instance variable


def setColor(self, color):
self.color = color

# Retrieves instance variable


def getColor(self):
return self.color

# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
 Python is an object oriented programming language.
 Almost everything in Python is an object, with its properties
and methods.
 A Class is like an object constructor, or a "blueprint" for
creating objects
Create a Class

To create a class, use the keyword class:

Ex: class MyClass:


x = 44
Create Object

Now we can use the class named MyClass to create objects:

p1 = MyClass()
print (p1.x)

A class is a user-defined blueprint or prototype from which objects


are created. Classes provide a means of bundling data and
functionality together. Creating a new class creates a new type of
object, allowing new instances of that type to be made. Each class
instance can have attributes attached to it for maintaining its state.
Class instances can also have methods (defined by their class) for
modifying their state.

To understand the need for creating a class let’s consider an example,


let’s say you wanted to track the number of dogs that may have
different attributes like breed, age. If a list is used, the first element
could be the dog’s breed while the second element could represent its
age. Let’s suppose there are 100 different dogs, then how would you
know which element is supposed to be which? What if you wanted to
add other properties to these dogs? This lacks organization and it’s
the exact need for classes.

Class creates a user-defined data structure, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an
object.

Some points on Python class:


 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot
(.) operator. Eg.: Myclass.Myattribute
Interfaces :
In object-oriented languages like Python, the interface is a collection
of method signatures that should be provided by the implementing
class. Implementing an interface is a way of writing an organized code
and achieve abstraction.
The package zope.interface provides an implementation of “object
interfaces” for Python. It is maintained by the Zope Toolkit project.
The package exports two objects, ‘Interface’ and ‘Attribute’ directly.
It also exports several helper methods. It aims to provide stricter
semantics and better error messages than Python’s built-in abc
module.
Declaring interface
In python, interface is defined using python class statements and is a
subclass of interface. Interface which is the parent interface for all
interfaces.
Syntax :
class IMyInterface (zope.interface. Interface):
# methods and attributes

import zope.interface
class MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self, x):
pass
def method2(self):
pass

print(type(MyInterface))
GMRIT S VINODKUMAR CSE
print(MyInterface. module )

GMRIT S VINODKUMAR CSE


print(MyInterface. name )

# get attribute
x = MyInterface['x']
print(x)
print(type(x))

Implementing interface

Interface acts as a blueprint for designing classes, so interfaces are


implemented using implementer decorator on class. If a class
implements an interface, then the instances of the class provide the
interface. Objects can provide interfaces directly, in addition to what
their classes implement.

Syntax :
@zope.interface.implementer(*interfaces)
class Class_name:
# methods

import zope.interface
class MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self, x):
pass
def method2(self):
pass
@zope.interface.implementer(MyInterface)
class MyClass:

GMRIT S VINODKUMAR CSE


def method1(self, x):
return x**2
def method2(self):
return "foo"

Methods

implementedBy(class) – returns a boolean value, True if class


implements the interface else False
providedBy(object) – returns a boolean value, True if object provides
the interface else False
providedBy(class) – returns False as class does not provide interface
but implements it
list(zope.interface.implementedBy(class)) – returns the list of
interfaces implemented by a class
list(zope.interface.providedBy(object)) – returns the list of interfaces
provided by an object.
list(zope.interface.providedBy(class)) – returns empty list as class
does not provide interface but
implements it.

Interface Inheritance
Interfaces can extend other interfaces by listing the other interfaces
as base interfaces.

Functions

extends(interface) – returns boolean value, whether one interface


extends another.

GMRIT S VINODKUMAR CSE


isOrExtends(interface) – returns boolean value, whether interfaces
are same or one extends another.
isEqualOrExtendedBy(interface) – returns boolean value, whether
interfaces are same or one is extended by another.

GMRIT S VINODKUMAR CSE


Python’s Http Package :

http is a package that collects several modules for


working with the HyperText Transfer Protocol:
 http.client is a low-level HTTP protocol client; for
high-level URL opening use urllib.request
 http.server contains basic HTTP server classes
based on socketserver
 http.cookies has utilities for implementing state
management with cookies
 http.cookiejar provides persistence of cookies

http is also a module that defines a number of HTTP


status codes and associated messages through
the http.HTTPStatus enum:

Components
http provides a few components to build HTTP
messages:
Headers: a class to manipulate HTTP headers
Request: a class to encapsulate a HTTP request
Response: a class to encapsulate a HTTP response
Date: a class to convert date to and from ISO 8601
Url: a class to manipulate url

How to get?
Install with “pip” command:
$ pip install http
Python’s Http Server :

Python HTTP server is a kind of web server that is used to


access the files over the request. Users can request any data
or file over the webserver using request, and the server
returns the data or file in the form of a response. The HTTP
server is one of the most famous and widely used servers, and
most of the websites still running on this protocol. HTTP is
generally preferred for the dev servers, not for the products.
Production server protocols need to be more secure. Python
provides inbuilt classes to make our HTTP server with the
help of that Python socket server. TCP Server has a subclass
HTTP Server. It is responsible for creating requests, and it
listens to HTTP sockets for handling the request.

Lets create a basic http web server:

from http.server import HTTPServer,


BaseHTTPRequestHandler
class CustomHandler(BaseHTTPRequestHandler):def
do_GET(self):
self.send_response(200)
self.send_header('content-type','text/html')
self.end_headers()
self.wfile.write('Python HTTP Webserver Tutorial'.encode())def
main():
PRT = 8000
srv = HTTPServer(('',PRT), CustomHandler)
print('Server started on port %s' %PRT)
srv.serve_forever()
if name == ' main ':
main()

Output:
Server started on port 8000
In the above example, we have imported HTTPServer from
http.server module and BaseHTTPRequestHandler class from
the same module. HTTPServer is going to handle all requests
like get requests or post requests. We have created a method
CustomHandler.Now we have defined our main method, and
here we are gonna serve our actual server. We have created a
variable PRT that will hold our port number. You can define
any port number that must be free. Then we created another
variable, srv that is holding the instance of the HTTPServer. It
takes two parameters; the first parameter is a tuple of
hostname and port number. We are running it on localhost so
we can leave it empty and port number. The second
parameter will be the request handler.
We have defined ‘CustomHandler’ as our request handler.
Then we have simply printed a message that will indicate that
our server is up and running. Now we have defined the
server.serve_forever method. This will start the server, and it
will keep running until we don’t stop it.

Now we have created a ‘CustomHandler’ that will be used to


handle all requests that the server receives. We have defined
BaseHTTPRequestHandler into the class; it will inherit all the
properties of the base request class. Now we have created the
do_GET method that takes self as an argument and service
should send back a response and the status codes like 200,
and it means the file which we are looking on the server is
found and will be displayed on the web page.
‘self.send_header’ is responsible for sending the headers
information like content type like HTML Page. We also have
to close the headers once we have listed them.

Now we will put some content that will load once the server
is running. ‘self.wfile.write’ is responsible for writing to the
file. We are using encode method because http servers cannot
send string on the http request, so encoding the string into
bias is served on the web page.

if name == ‘ main ’: this means that this file is running


directly and we haven’t imported it. So now we can execute
this program, python will execute the main method, and we
can use our port number and localhost in the browser to
check if our server is running or not. “localhost:8000”use this
address in the url bar and hit enter. You might see the
message that you have written along with the port number
which we have defined.

Now you can change the output message, but you won’t be
able to see the change if we refresh. We need to stop the
server and execute the program again.

We are using BaseHTTPRequestHandler for creating our


server.

We have the following instance variables.

client_address: It is a tuple that refers to a client address


containing hostname and port.
close_connection: It is a boolean value that is set before the
handle_one_request(); it indicates whether another request is
being created or the current connection is closed.
path: It contains the path of the request.
headers: It is used to hold the instance of the file that is
created by the message class. This instance is responsible for
parsing the HTTP Request.
wfile: It is responsible for writing the stream to the client-
side. The proper HTTP protocol is followed for achieving
successfully writing to http clients.
protocal_version: It tells the version of the HTTP Protocol. If
the permission is HTTP/1.1, then the server will allow
persistent http connections. It is important to mention the
length of the content in all request responses to the client.
Creating Server that supports CRUD :

Coding the Models.py

Here, we will use Flask_SQLAlchemy and SQLite DB.

First install Flask_SQLAlchemy

$ pip install -U Flask-SQLAlchemy


Now create a models.py file and add the following
code:
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class EmployeeModel(db.Model):
__tablename__ = "table"

id = db.Column(db.Integer, primary_key=True)
employee_id = db.Column(db.Integer(),unique =
True)
name = db.Column(db.String())
age = db.Column(db.Integer())
position = db.Column(db.String(80))

def __init__(self, employee_id,name,age,position):


self.employee_id = employee_id
self.name = name
self.age = age
self.position = position

def __repr__(self):
return f"{self.name}:{self.employee_id}"

2. Coding the main Application :


Now, lets code our main Flask Application File. We’ll
begin by importing Flask, initialize the flask app, and
set up the application runtime details.
from flask import Flask

app = Flask(__name__)

app.run(host='localhost', port=5000)
Now we need to link SQLite DB with SQLAlchemy.
So add the following code snippet:
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =
'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'
] = False

app.run(host='localhost', port=5000)
Replace <db_name> with the name you want for
your DB File.
from flask import Flask
app =Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =
'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'
] = False
db.init_app(app)

@app.before_first_request
def create_table():
db.create_all()

app.run(host='localhost', port=5000)
3. Coding the Create view :
The Create view should be able to do the following:
• When the Client goes to this page (GET method),
it should display a Form to get the Client’s Data.
• On Submission (POST method), it should save
the Client’s data in the EmployeeModel
Database.
So the Create View will be:
@app.route('/data/create' , methods =
['GET','POST'])
def create():
if request.method == 'GET':
return render_template('createpage.html')

if request.method == 'POST':
employee_id = request.form['employee_id']
name = request.form['name']
age = request.form['age']
position = request.form['position’]
employee =
EmployeeModel(employee_id=employee_id,
name=name, age=age, position = position)
db.session.add(employee)
db.session.commit()
return redirect('/data')
The createpage.html will contain the HTML Form:
<form action='' method = "POST">
<p>employee ID <input type = "integer" name =
"employee_id" /></p>
<p>name <input type = "text" name = "name"
/></p>
<p>age <input type = "integer" name = "age"
/></p>
<p>position <input type = "text" name = "position"
/></p>
<p><input type = "submit" value = "Submit"
/></p>
</form>

4. Coding the Retrieve views


Here we will have 2 views:
• To display the list of Employees.
• To display the information of a single Employee.
So the First RetrieveDataList view will be:
@app.route('/data')
def RetrieveDataList():
employees = EmployeeModel.query.all()
return render_template('datalist.html',employees
= employees)
The datalist.html file will display the list of
Employees:
{% for employee in employees %}
<h3>{{employee}}</h3><hr>
{% endfor %}
Do check out our Flask Template to know more
about the template language.

And the Second RetrieveSingleEmployee View


will be:
@app.route('/data/<int:id>')
def RetrieveSingleEmployee(id):
employee =
EmployeeModel.query.filter_by(employee_id=id).firs
t()
if employee:
return render_template('data.html', employee =
employee)
return f"Employee with id ={id} Doenst exist"
EmployeeModel.query.filter_by(employee_id =
id).first() will return the first Employee with
Employee ID = id in the DB or return None if the
Employee with that id does not exist.

The data.html displays the information of the


Employee:
<h3>Id</h3>
<p>{{employee.employee_id}}</p><hr>
<h3>Name</h3>
<p>{{employee.name}}</p><hr>
<h3>Age</h3>
<p>{{employee.age}}</p><hr>
<h3>Position</h3>
<p>{{employee.position}}</p><hr>

5. Coding the Update View :


The Update View will update the Employee details in
the DB with the new one submitted by the user.
Hence the Update View will be:

@app.route('/data/<int:id>/update',methods =
['GET','POST'])
def update(id):
employee =
EmployeeModel.query.filter_by(employee_id=id).firs
t()
if request.method == 'POST':
if employee:
db.session.delete(employee)
db.session.commit()

name = request.form['name']
age = request.form['age']
position = request.form['position']
employee = EmployeeModel(employee_id=id,
name=name, age=age, position = position)

db.session.add(employee)
db.session.commit()
return redirect(f'/data/{id}')
return f"Employee with id = {id} Does nit exist"

return render_template('update.html', employee =


employee)

-> The user will submit the new details via the
Form. Here we first delete the old information
present in the DB and then add the new information.
The update.html displays the Form for the
submission of new details:

<form action='' method = "POST">


<p>name <input type = "text" name = "name"
value="{{employee.name}}"/></p>
<p>age <input type = "integer" name =
"age" value="{{employee.age}}"/></p>
<p>position <input type = "text" name = "position"
value="{{employee.position}}"/></p>
<p><input type = "submit" value = "Submit"
/></p>
</form>

6. Coding the Delete View :


The Delete View will just delete the Employee
Information from the DB File.
The Delete View will be:
@app.route('/data/<int:id>/delete',
methods=['GET','POST'])
def delete(id):
employee =
EmployeeModel.query.filter_by(employee_id=id).firs
t()
if request.method == 'POST':
if employee:
db.session.delete(employee)
db.session.commit()
return redirect('/data')
abort(404)

return render_template('delete.html')
The delete.html just re-confirms the deletion:
<form action='' method="post">
Click YES to confirm
<input type = "submit" value="YES">
<a href='/data'>Cancel</a>
</form>
If the user presses Yes then the Employee is deleted.
Or else he is taken back.

You might also like