20CSC21Notes 4
20CSC21Notes 4
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
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.
print ("\r")
print("\r")
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 :
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()
The self :
__init__ method
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
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.
# Class Variable
animal = 'dog'
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)
# Instance Variable
self.breed = breed
# 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
p1 = MyClass()
print (p1.x)
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.
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 )
# get attribute
x = MyInterface['x']
print(x)
print(type(x))
Implementing interface
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:
Methods
Interface Inheritance
Interfaces can extend other interfaces by listing the other interfaces
as base interfaces.
Functions
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 :
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 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.
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.
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 __repr__(self):
return f"{self.name}:{self.employee_id}"
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>
@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"
-> 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:
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.