You are on page 1of 77

PFSD

Lab manual
SET 1
PFSD
Lab manual
SET 2
PRACTICAL-1
 AIM : A program that models a bank account, with classes for the
account, the customer, and the bank

Problem Statement:
Create a program that models a bank account system. The system should consist of classes
representing the bank account, the customer, and the bank itself.

Program Description:
The program will simulate basic banking operations such as creating a new account, depositing
and withdrawing money, checking the account balance, and managing customer information. It
will use object-oriented programming principles with classes to organize and structure the data
and behavior.

Algorithm:
1. Define a Customer class with attributes like customer ID, name, address, and contact details.
2. Create a BankAccount class with attributes such as account number, account holder (linked to a
Customer), balance, and account type (e.g., savings or checking).
3. Implement methods in the BankAccount class for deposit, withdrawal, and checking the account
balance.
4. Develop a Bank class to manage a collection of accounts, allowing the creation of new accounts,
retrieval of account details, and overall management of the bank.

Source Code:
import random

class Customer:
def __init__(self, name, address, contact_number):
self.name = name
self.address = address
self.contact_number = contact_number
self.accounts = []

def create_account(self, account_type, ini al_balance):


account_number = Bank.generate_account_number()
account = BankAccount(account_type, ini al_balance, self, account_number)
self.accounts.append(account)
return account

def display_customer_info(self):
print(f"Customer Name: {self.name}")
print(f"Address: {self.address}")
print(f"Contact Number: {self.contact_number}")
print("Accounts:")

for account in self.accounts:


print(f" - {account}")

class BankAccount:
def __init__(self, account_type, balance, owner, account_number):
self.account_type = account_type
self.balance = balance
self.owner = owner
self.account_number = account_number

def deposit(self, amount):


self.balance += amount
print(f"Deposited INR {amount}. New balance: INR {self.balance}")

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
print(f"Withdrew INR {amount}. New balance: INR {self.balance}")
else:
print("Insufficient funds!")

def __str__(self):
return f"{self.account_type} Account - Account Number: {self.account_number}, Balance: INR
{self.balance}"

class Bank:
def __init__(self, name):
self.name = name
self.customers = []

def add_customer(self, customer):


self.customers.append(customer)

@sta cmethod
def generate_account_number():
return ''.join(random.choice('0123456789') for _ in range(8))

def display_bank_info(self):
print(f"Bank Name: {self.name}")
print("Customers:")
for customer in self.customers:
customer.display_customer_info()
print()

def find_account_by_number(self, account_number):


for customer in self.customers:
for account in customer.accounts:

2
if account.account_number == account_number:
return account
return None

# Example usage
if __name__ == "__main__":
# Create a bank
my_bank = Bank("My Bank")
customer_list=[]
while True:
print("1. New Customer 2. Exis ng Customer 3. Find Customers info 4.Exit")
try:
choice = int(input())

if choice==1:
print("Customer Registra on: \n")
# Create a customer
name=input("Enter Customer Name:")
address=input('Enter Customer Address: ')
contact_number=input("Enter Customer Contact Number: ")
customer_obj = Customer(name, address, contact_number)
customer_list.append(customer_obj)
my_bank.add_customer(customer_obj)
while True:
acc_type = int(input("Enter 1. To create Saving account 2. To Create Cheking account 3. Exit\n"))
if acc_type == 1:
new_account = customer_obj.create_account("Savings", 1000)
print(f"Savings account created with account number: {new_account.account_number}\n")
break
elif acc_type == 2:
new_account = customer_obj.create_account("Current", 1000)
print(f"Current account created with account number: {new_account.account_number}\n")
break

elif acc_type == 3:
break
else:
print("Invalid op on....Try again")

if choice==2:
# User input for transac ons
account_number_input = input("Enter your account number: ")
account_to_transact = my_bank.find_account_by_number(account_number_input)

if account_to_transact:
print(f"\nWelcome, {account_to_transact.owner.name}!")
print(account_to_transact)
while True:
print("1. Enter 1 to deposit\n2. Enter 2 to Withdrawl\n3. Enter 3 to Check the Balance\n4. Exit")
op on=int(input("Enter your Op on:\n"))

3
if op on==1:
print("Welcome to Deposit Sec on\n")
# Deposit
deposit_amount = int(input("\nEnter the amount to deposit: INR "))
account_to_transact.deposit(deposit_amount)
elif op on==2:
print("Welcome to withdrawl sec on:\n")
# Withdrawal
withdrawal_amount = int(input("\nEnter the amount to withdraw: INR "))
account_to_transact.withdraw(withdrawal_amount)
elif op on==3:
# Display updated account informa on
print("\nUpdated Account Informa on:")
print(account_to_transact)
elif op on==4:
break
else:
print("Invalid Op on")
else:
print("Account not found.")
if choice==3:
my_bank.display_bank_info()
elif choice==4:
break
else:
pass
except ValueError:
print("Invalid input. Please enter a valid op on.")
con nue

4
Class Diagram:

Expected Output:

5
Actual Output:

Result:
The result will be a program that allows users to create bank accounts, perform transactions, and
manage customer and account information.

6
PRACTICAL- 2
 AIM: A program that simulates a school management system, with
classes for the students, the teachers, and the courses.

Problem Statement:
Develop a program that simulates a school management system, modeling classes for students,
teachers, and courses. The system should allow for the creation of students and teachers,
enrollment in courses, grading, and tracking of academic information.

Program Description:
The program will use object-oriented programming to represent students, teachers, and courses.
Students can enroll in courses, teachers can assign grades, and the system will maintain academic
records for each student.

Algorithm:
1. Define a Student class with attributes like student ID, name, address, contact details, and a
method to enroll in courses.
2. Create a Teacher class with attributes such as teacher ID, name, subject expertise, and a method
to assign grades to students.
3. Implement a Course class with attributes like course code, course name, and a list of enrolled
students.
4. Develop a SchoolManagementSystem class to manage students, teachers, and courses, allowing
the creation of new students and teachers, enrollment in courses, and grading.

Source Code:
class Student:
def __init__(self, student_id, name, grade):
self.student_id = student_id
self.name = name
self.grade = grade

def display_info(self):
print(f"\nStudent ID: {self.student_id}, Name: {self.name}, Grade: {self.grade}")

class Teacher:
def __init__(self, teacher_id, name, subject):
7
self.teacher_id = teacher_id
self.name = name
self.subject = subject

def display_info(self):
print(f"\nTeacher ID: {self.teacher_id}, Name: {self.name}, Subject: {self.subject}")

class Course:
def __init__(self, course_code, course_name, teacher, students):
self.course_code = course_code
self.course_name = course_name
self.teacher = teacher
self.students = students

def display_info(self):
print(f"\nCourse Code: {self.course_code}, Course Name: {self.course_name}")
print("\nTeacher:")
self.teacher.display_info()
print("\nStudents:")
for student in self.students:
student.display_info()

def main():
students = []
teachers = []
courses = []
print("""1.Student_form/details
2.Teacher_form/details
3.Course_form/details""")
cho = int(input("\nEnter your choice: "))

if cho == 1:
num_students = int(input("\nEnter the number of students: "))
for i in range(num_students):
student_id = input(f"\nEnter student {i + 1} ID: ")
name = input(f"\nEnter student {i + 1} name: ")
grade = input(f"\nEnter student {i + 1} grade: ")
students.append(Student(student_id, name, grade))
print("\nRegistra on successful.")

elif cho == 2:
num_teachers = int(input("\nEnter the number of teachers: "))
for i in range(num_teachers):
teacher_id = input(f"\nEnter teacher {i + 1} ID: ")
name = input(f"\nEnter teacher {i + 1} name: ")
subject = input(f"\nEnter teacher {i + 1} subject: ")
teachers.append(Teacher(teacher_id, name, subject))
8
print("\nRegistra on successful.")

elif cho == 3:
num_courses = int(input("\nEnter the number of courses: "))
for i in range(num_courses):
course_code = input(f"\nEnter course {i + 1} code: ")
course_name = input(f"\nEnter course {i + 1} name: ")
teacher_index = int(input("\nEnter the index of the teacher for this course: "))
teacher = teachers[teacher_index]
student_indices = input("\nEnter the indices of students for this course (comma-separated): ")
student_indices = student_indices.split(",")
students_for_course = [students[int(index)] for index in student_indices]
courses.append(Course(course_code, course_name, teacher, students_for_course))
print("\nRegistra on successful.")

else:
print("\nInvalid input")

if __name__ == "__main__":
main()

Class Diagram:

9
Expected Output:

Actual Output:

Result:
The program successfully calculates the area and perimeter of a rectangle based on the user's
choice. It provides a user-friendly interface and accurate results for the calculations, meeting the
goal of creating a rectangle calculator.

10
PRACTICAL- 3
 AIM: A program that reads a text file and counts the number of words in
it.

Problem Statement:
Develop a program that reads a text file and counts the number of words in it.

Program Description:
The program will take a text file as input, read its content, and count the number of words. A
word is defined as any sequence of characters separated by whitespace.

Algorithm:
1. Open the text file in read mode.
2. Read the content of the file.
3. Tokenize the content based on whitespace to extract words.
4. Count the number of words.
5. Print the result.

Source Code:
def count(path):
try:
with open(path,'r') as file:
file_content = file.read()
return f"data = {file_content.split()}\nlength of the words:
{len(file_content.split())}"
except FileNotFoundError:
return "Please Provide valid file path."

path ="example.txt"
print(count(path))

Expected Output:

11
Actual Output:

Result:
The result will be the count of words in the specified text file.

12
PRACTICAL- 4
 AIM: A program that reads a CSV file and calculates the average of the
values in a specified column.

Problem Statement:
Develop a program that reads a CSV file, extracts data from a specified column, and calculates
the average of the values in that column.

Program Description:
The program will take a CSV file as input, read its content, and allow the user to specify a column
for which the average should be calculated. It will then perform the necessary calculations and
display the average value.

Algorithm:
1. Accept the CSV file path and column name from the user.
2. Open and read the CSV file, extracting the specified column data.
3. Convert the column values to numerical format (assuming the values are numerical).
4. Calculate the average of the values in the specified column.
5. Display the result.

Source Code:
import csv

def calculate_average(csv_file, column_name):


try:
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
if column_name not in reader.fieldnames:
print(f"Column '{column_name}' not found in the CSV file.")
return None
total = 0
count = 0
for row in reader:
try:
value = float(row[column_name])
total += value
count += 1
except ValueError:
print(f"Skipping row {reader.line_num}: Invalid value in column '{column_name}'.")
if count == 0:
print(f"No valid values found in column '{column_name}'.")
13
return None
average = total / count
return average

except FileNotFoundError:
print(f"File '{csv_file}' not found.")
return None
csv_file_path = 'file.csv'
column_to_calculate = 'ENGLISH'

result = calculate_average(csv_file_path, column_to_calculate)

if result is not None:


print(f"The average value in column '{column_to_calculate}' is: {result}")

file.csv:

Expected Output:

Actual Output:

14
Result:
The result is the average value of the specified column in the provided CSV file. You can
customize and expand this program based on your specific requirements and the structure of your
CSV file.

15
PRACTICAL- 5
 AIM: A program that reads an Excel file and prints the data in
a tabular format.

Problem Statement:
Develop a program that reads an Excel file and prints its data in a tabular format.

Program Description:
The program will take an Excel file as input, read its content, and display the data in a tabular
format. It may use libraries like openpyxl or pandas to handle Excel file operations.

Algorithm:
1. Accept the Excel file path from the user.
2. Open and read the Excel file.
3. Extract the data from the sheets.
4. Display the data in a tabular format.

Source Code:
import pandas as pd

import openpyxl

output = pd.read_excel("delimited.xlsx")

print(output)

16
delimited.xlsx:

Expected Output:

17
Actual Output:

Result:
The result is the data from the Excel file displayed in a structured tabular format. You can
customize and extend this program based on your specific requirements and the structure of your
Excel file.

18
PFSD
Lab manual
SET 3
SET-3

PRACTICAL-1
❖ AIM : A program that creates a simple web server and serves a static HTML
page.

Problem Statement:
Develop a Python program that creates a simple web server using Flask and serves a static HTML
page. The web server should be able to handle incoming requests and respond by rendering the
provided HTML page. The goal is to understand the basics of setting up a web server and serving
static content using Flask.

Program Description:
Develop a Python program using Flask to create a simple web server serving a static HTML page. The
objective is to use the flask command (flask --app <YourAppName> run) instead of running the
script directly. Ensure proper project organization, write a basic HTML file, and confirm functionality
by accessing http://127.0.0.1:5000/ in a web browser.

Procedure:
Step 1: Install Flask

Make sure Flask is installed. Open a terminal and run the following command:

bash

pip install Flask

Step 2: Create Project Structure

Create a folder for your project and inside it, create two files - app.py for your Flask application and
a folder named templates to store the HTML file.

project_folder/

|-- app.py

|-- templates/

| |-- index.html

Step 3: Write the HTML File


Open templates/index.html in a text editor and write a simple HTML structure. For example:

index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Static HTML Page</title>

</head>

<body>

<h1>Hello World!</h1>

</body>

</html>

Step 4: Write the Flask App

Open app.py in a text editor and write the Flask application code:

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")

def home():

return render_template("index.html")

if __name__ == "__main__":

app.run(debug=True)

Step 5: Run the Flask App


2
In the terminal, navigate to the project folder and run the Flask app using the flask command:

bash

flask --app app run

Expected Output:

Actual Output:

Result:
Upon executing the provided Python program using Flask and the flask command (flask --app
<YourAppName> run), navigate to http://127.0.0.1:5000/ in a web browser. You should see a static
HTML page with the expected content, confirming the successful setup of a basic web server.

3
PRACTICAL- 2
❖ AIM: A program that creates a web application that allows users to register
and login.

Problem Statement:
Develop a Python program that creates a web application allowing users to register and login. The
objective is to implement user authentication functionalities using Flask, ensuring secure and seamless
user interaction.

Program Description:
The web application will be built using a combination of front-end and back-end technologies. The
front-end will be responsible for creating the user interface, while the back-end will handle user
registration, login authentication, and data storage.

Procedure:
1. Setup:

Make sure you have Python installed on your system. Install Flask and Flask-
SQLAlchemy:

bash
pip install Flask Flask-SQLAlchemy

2. Create Project Structure :

Create a folder for your project and inside it, create two files - app.py for your Flask application and
a folder named templates to store the HTML file.

project_folder/

|-- app.py

|-- templates/

| |-- index.html

| |-- login.html

| |-- register.html

4
3. Write the html files:

Write the index.html, login.html, register.html and design using CSS(Cascading


stylesheet):
index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Static HTML Page</title>
</head>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: #ff5a5f;
}
h1 {
font-family: "Poppins", sans-serif;
color: #fff;
margin: 30px 50px;
font-size: 3rem;
}
input {
padding: 10px 20px;
border: 3px solid #fff;
border-radius: 10px;
background: rgb(16, 208, 16);
font-size: 1.5rem;
color: white;
font-family: "Poppins", sans-serif;
font-weight: 300;
transition: .3s;
&:hover{
background: #fff;
color: #000;
cursor: pointer;
5
}
}
</style>
<body>
<h1>Hello, this is a static HTML page served by Flask!</h1>
<form action="{{ url_for('register') }}">
<input type="submit" value="Register" />
</form>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Login</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background: rgb(9, 9, 121);
background: linear-gradient(
30deg,
rgba(9, 9, 121, 1) 0%,
rgba(2, 0, 36, 1) 29%,
rgba(0, 212, 255, 1) 100%
);
}
.container {
display: flex;
align-items: center;
justify-content: space-evenly;
flex-direction: column;
width: 600px;
border-radius: 20px;
height: 500px;
background: #ffffff5a;
6
backdrop-filter: blur(20px);
& h1 {
font-family: Arial, Helvetica, sans-serif;
color: #fff;
margin: 30px 0;
}
& li {
list-style: none;
}
& form {
& label {
color: white;
font-family: Arial, Helvetica, sans-serif;
font-size: 1.4rem;
margin: 10px 20px;
}
& .log_button {
color: #fff;
background: red;
border: none;
outline: none;
padding: 5px 10px;
border-radius: 10px;
font-size: 1.2rem;
transition: 0.3s;
transform: translateX(130px);
&:hover {
background: #fff;
color: #000;
cursor: pointer;
}
}
& .password{
padding: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& .username{
padding: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& input {
margin: 10px 20px;
}
}
}
.error {
color: red;
}
7
.success {
color: green;
}
.default {
color: black;
}
</style>
</head>
<body>
<div class="container">
<h1>User Login</h1>
{% with messages = get_flashed_messages() %} {% if messages %}
<ul>
{% for message in messages %}
<li
class="{% if 'error' in message %}error{% elif 'success' in message %}success{% else %}default{% endif
%}"
>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %} {% endwith %}
<form method="post" action="{{ url_for('login') }}">
<label for="username" class="username_label">Username:</label>
<input type="text" name="username" class="username" required />
<br />
<label for="password" class="password_label">Password:</label>
<input type="password" name="password" class="password" required />
<br />
<input type="submit" class="log_button" value="Log in" />
</form>
<p>
Don't have an account?
<a href="{{ url_for('register') }}">Register here</a>.
</p>
</div>
</body>
</html>

register.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Registration</title>
<style>
8
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background: rgb(9, 9, 121);
background: linear-gradient(
30deg,
rgba(9, 9, 121, 1) 0%,
rgba(2, 0, 36, 1) 29%,
rgba(0, 212, 255, 1) 100%
);
}
.container {
display: flex;
align-items: center;
justify-content: space-evenly;
flex-direction: column;
width: 600px;
border-radius: 20px;
height: 500px;
background: #ffffff5a;
backdrop-filter: blur(20px);
& h1 {
font-family: Arial, Helvetica, sans-serif;
color: #fff;
margin: 30px 0;
}
& li {
list-style: none;
}
& form {
& label {
color: white;
font-family: Arial, Helvetica, sans-serif;
font-size: 1.4rem;
margin: 10px 20px;
}
& .register_button {
color: #fff;
background: red;
border: none;
outline: none;
padding: 5px 10px;
border-radius: 10px;
9
font-size: 1.2rem;
transition: 0.3s;
transform: translateX(130px);
&:hover {
background: #fff;
color: #000;
cursor: pointer;
}
}
& .password {
padding: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& .username {
padding: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& input {
margin: 10px 20px;
}
}
}
.error {
color: red;
}
.success {
color: green;
}
.default {
color: black;
}
</style>
</head>
<body>
<div class="container">
<h1>User Registration</h1>
{% with messages = get_flashed_messages() %} {% if messages %}
<ul>
{% for message in messages %}
<li
class="{% if 'error' in message %}error{% elif 'success' in message %}success{% else %}default{% endif
%}"
>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %} {% endwith %}
10
<form method="post" action="{{ url_for('register') }}">
<label for="username" class="username_label">Username:</label>
<input type="text" name="username" class="username" required />
<br />
<label for="password" class="password_label">Password:</label>
<input type="password" name="password" class="password" required />
<br />
<input type="submit" class="register_button" value="Register" />
</form>
<p>
Already have an account?
<a href="{{ url_for('login') }}">Log in here</a>.
</p>
</div>
</body>
</html>

4. Run the Application:

Copy the provided Python code into a file named app.py.

app.py
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(256), nullable=False)

with app.app_context():
db.create_all()
@app.route("/")
def home():
return render_template("index.html")

@app.route('/register', methods=['GET', 'POST'])


def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

if User.query.filter_by(username=username).first():
flash('Username already taken. Please choose another.', 'error')
else:
hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
new_user = User(username=username, password=hashed_password)
db.session.add(new_user)

11
db.session.commit()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))

return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])


def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

user = User.query.filter_by(username=username).first()

if user and check_password_hash(user.password, password):


session['username'] = username
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password. Please try again.', 'error')

return render_template('login.html')

@app.route('/dashboard')
def dashboard():
if 'username' in session:
return f'Welcome to the dashboard, {session["username"]}!'
else:
flash('Please log in to access the dashboard.', 'info')
return redirect(url_for('login'))

@app.route('/logout')
def logout():
session.pop('username', None)
flash('You have been logged out.', 'info')
return redirect(url_for('login'))

if __name__ == '__main__':
app.run(debug=True)

5. Open a terminal and run the application inside the directory whereapp.py file is stored
and run the following command:

bash
flask -–app app run

6. The application will be accessible at http://127.0.0.1:5000/ in your web browser.


Access Home Page:
• Navigate to http://127.0.0.1:5000/.
• The home page should be rendered, displaying a link to the login page.

7. User Registration:
8. Click on the "Register here" link.
12
• Enter a unique username and password in the registration form.
• Submit the form to register and receive a success message.
9. User Login:
• Go back to the login page.
• Enter the registered credentials and log in.
• Receive a login success message.
10.Dashboard Access:
• Navigate to http://127.0.0.1:5000/dashboard.
• Access the protected dashboard route, displaying a welcome message with
the username.
11.Logout:
• Click on the "Logout" link.
• Log out and receive a logout success message.
12.Database Exploration:
• Check the SQLite database file (users.db) to see the stored user
information.
13.Customization:
• Modify HTML templates (login.html and register.html) for appearance
changes.
• Explore Flask features for additional functionalities and security
enhancements.
14.Testing:
• Test different scenarios, such as attempting to register with an existing
username, entering incorrect login credentials, and accessing the
dashboard without logging in.
15.Further Enhancements:
• Add more features, such as password reset functionality, email
verification, or profile management.
• Implement stronger security measures, like using Flask-WTF for form
handling and Flask-Login for user session management.

13
Expected Output:

14
Result:
Upon successful completion of the registration and login processes, the web application will display
a confirmation message or redirect the user to a dashboard page. Additionally, the user's information
will be securely stored in the database for future logins. The application will provide a secure and
user-friendly experience for managing user accounts on the web platform.

15
PRACTICAL- 3
❖ AIM: A program that creates a web application that allows users to upload
and download files.

Problem Statement:
Create a Flask web application for file management, allowing users to upload and download files. The
application should provide a user-friendly interface with a file upload form, display a list of uploaded
files, and enable users to download files from the list.

Program Description:
Develop a Flask-based web application featuring:

1. File Upload:
• Users can upload files through a web form.
• Prevent form submission without selecting a file.
• Save uploaded files to a server directory (e.g., uploads).
2. File Display:
• Display a dynamic list of uploaded files on the main page.
• Each file entry includes a "Download" button.
3. File Download:
• Enable users to download files by clicking the corresponding "Download" button.
4. User Interface:
• Design a clean and user-friendly interface using HTML templates.
• Separate application code (app.py) and HTML templates.

Procedure:
1. Setup:
• Make sure you have Python installed on your system.
• Install Flask:

bash

pip install Flask

2. Project structure:

project_folder/

|-- app.py

|-- templates/

16
| |-- index.html

3. Write html files:


Write index.html file and style it:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload and Download</title>
</head>
<body>
<h1>File Upload and Download</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file" required>
<br>
<input type="submit" value="Upload">
</form>

<h2>Uploaded Files</h2>
{% for filename in filenames %}
<div>
<span>{{ filename }}</span>
<a href="{{ url_for('download_file', filename=filename) }}" download>
<button>Download</button>
</a>
</div>
{% endfor %}
</body>
</html>

4. Run the Application:


• Copy the provided Python code into a file named app.py.

app.py
from flask import Flask, render_template, request, send_from_directory,
redirect, url_for
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

17
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@app.route('/')
def index():
filenames = os.listdir(app.config['UPLOAD_FOLDER'])
return render_template('index.html', filenames=filenames)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return "No file part"
file = request.files['file']
if file.filename == '':
return "No selected file"
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return redirect(url_for('index'))
@app.route('/download/<filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True)

• Create a folder named uploads in the same directory as app.py to store uploaded files.
• Open a terminal and open the directory where the app.py file is saved and run the command:

bash
flask –-app app run

• The application will be accessible at http://127.0.0.1:5000/ in your web browser.


1. File Upload:
• Navigate to http://127.0.0.1:5000/.
• Use the file input form to choose a file and click "Upload."
• The uploaded file will be saved in the uploads folder.
2. File Download:
• View the list of uploaded files on the same page.
18
• Each file has a "Download" button.
• Click on the "Download" button next to a file to download it.
3. Customization:
• Modify HTML template (index.html) for appearance changes.
• Explore Flask features for additional functionalities, such as handling different file types or
implementing user authentication.
4. Testing:
• Test by uploading various file types and sizes.
• Download the uploaded files to verify the functionality.

• This comprehensive procedure includes the Python code, HTML template, and steps to run,
use, and customize the Flask application for file upload and download.
• Expected Output:

Result:
Upon completion, users can:
• Upload files using the provided form.
• View a list of uploaded files with download options.

19
• Download files from the dsisplayed list.
• Experience an organized and visually appealing file management interface.

20
PRACTICAL- 4
❖ AIM: A program that creates a web application that displays data from a
database in a tabular format.

Problem Statement:
Develop a Flask web application that retrieves and displays data from a database in a tabular format.
The program should use SQLAlchemy to interact with the database and Pandas to format the data into
an HTML table.

Program Description:
The program utilizes Flask, SQLAlchemy, and Pandas to create a web application. It defines a simple
SQLAlchemy model (Person) to represent data with attributes like name and age. Sample data is
inserted into an SQLite database. The main route (/) queries the database, converts the data to a Pandas
DataFrame, and renders it as an HTML table using a Flask template (index.html).

Procedure:
1. Setup:
• Ensure you have Python installed on your system.
• Install Flask and SQLAlchemy:
bash
pip install Flask Flask-SQLAlchemy pandas

2. Project structure:

project_folder/

|-- app.py

|-- templates/

| |-- index.html

3. Write the html files:

Write index.html file:


index.html
<!DOCTYPE html>
<html lang="en">
<head>
21
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Display</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Data Display</h1>
<!-- Render the HTML table -->
{{ table_html | safe }}
</div>
</body>
</html>

4. Run the Application:


• Copy the provided Python code into a file named app.py.
app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import pandas as pd

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

# Create a SQLAlchemy instance


db = SQLAlchemy(app)

# Define a model for the data


class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
age = db.Column(db.Integer, nullable=False)

# Sample data for demonstration


sample_data = [{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 22}]

# Populate the database with sample data


with app.app_context():
db.create_all()
for entry in sample_data:
person = Person(name=entry['name'], age=entry['age'])
db.session.add(person)
db.session.commit()

# Define a route to display data in tabular format


22
@app.route('/')
def display_data():
# Query data from the database
data = Person.query.all()

# Convert the data to a Pandas DataFrame


df = pd.DataFrame([(person.name, person.age) for person in data], columns=['name', 'age'])

# Convert the DataFrame to HTML for rendering in the template


table_html = df.to_html(classes='table table-striped', index=False)

return render_template('index.html', table_html=table_html)

if __name__ == '__main__':
app.run(debug=True)

• Open a terminal and go to the directory where the app.py file is stored and run the application:
bash
flask –-app app run

• The application will be accessible at http://127.0.0.1:5000/ in your web browser.


5. Access Tabular Data:
• Navigate to http://127.0.0.1:5000/.
• Observe the tabular display of data retrieved from the database.
6. Database Interaction:
• Explore the SQLite database (example.db) created by the application.
• Observe how the sample data is inserted into the database during application startup.
7. Customization:
• Modify HTML template (index.html) for appearance changes.
• Adjust the SQLAlchemy model (Person) or database configurations for different data structures.
8. Testing:
• Test with various data sets to observe how the tabular display adjusts dynamically.

23
• Expected Output:

Result:
Upon completion of the steps, you will have a running Flask web application that
retrieves data from a database and displays it in a tabular format on the main page.
The application showcases the integration of SQLAlchemy and Pandas to handle
database interaction and data presentation.

24
PRACTICAL- 5
❖ AIM: A program that creates a web application that accepts user input and
sends it to a server-side script for processing.

Problem Statement:
Develop a Flask web application that allows users to input data via a form on the main page. The
program should process the user input on the server side and display the result back to the user.

Program Description:
You are tasked with creating a web application using Flask that enables users to input data on the main
page through a form. The entered data should be sent to the server, processed by a server-side script,
and the result displayed on the same page. The provided code includes a basic structure for achieving
this, where user input is obtained from a form, and a simple processing logic is applied.

Procedure:
1. Setup:
• Ensure you have Python installed on your system.
• Install Flask:

bash
pip install Flask

2. Project Structure:
project_folder/

|-- app.py

|-- templates/

| |-- index.html

3. Write html file:

Write index.html file:

25
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Input</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
background: #a2d2ff;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.container {
display: flex;
align-items: center;
justify-content: space-evenly;
flex-direction: column;
width: 500px;
height: 600px;
border-radius: 20px;
background: #ffffff5a;
backdrop-filter: blur(20px);
& h1{
font-family: Arial, Helvetica, sans-serif;
color: #3a86ff;
font-size: 2rem;
}
& label{
color: #3a86ff;
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2rem;
padding: 10px;
margin: 10px 20px;
}
& .enter{
padding: 10px 20px;
border: none;
outline: none;
border-radius: 20px;
}
26
& .submit{
padding: 10px 20px;
color: #fff;
background: #2a9d8f;
outline: none;
border: none;
border-radius: 10px;
transition: .3s;
transform: translateX(150px);
margin: 30px;
&:hover{
color: #000;
cursor: pointer;
background: #fff;
}
}
& h2{
font-family: Arial, Helvetica, sans-serif;
color: #3a86ff;
font-size: 2rem;
}
}
</style>
<body>
<div class="container">
<h1>User Input Form</h1>
<form method="post" action="/">
<label for="user_input">Enter something:</label>
<input type="text" class="enter" name="user_input" id="user_input" required />
<br />
<input class="submit" type="submit" value="Submit" />
</form>

{% if result %}
<div>
<h2>Result:</h2>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
</body>
</html>

4. Run the Application:


• Copy the provided Python code into a file named app.py.

app.py

from flask import Flask, render_template, request


app = Flask(__name__)
27
# Define a route for the main page
@app.route('/', methods=['GET', 'POST'])
def index():
result = None
if request.method == 'POST':
# Get user input from the form
user_input = request.form.get('user_input')
result = f"You entered: {user_input}"
return render_template('index.html', result=result)

if __name__ == '__main__':
app.run(debug=True)

• Open a terminal and run the application:

bash
flask --app app run

• The application will be accessible at http://127.0.0.1:5000/ in your web browser.

5. Access the Web Application:

• Navigate to http://127.0.0.1:5000/.
• Observe the main page with a form that has an input field.

6. User Input:

• Enter text into the input field and submit the form.

7. Server-side Processing:

• Observe how the entered data is processed on the server side.


• The provided code processes the input by displaying a message. You can replace this with your
own processing logic.

8. Result Display:

• View the result displayed on the same page, indicating the processed user input.
• The result is dynamically updated based on the user's input and server-side processing.

9. Customization:

• Modify HTML template (index.html) for appearance changes.


• Adjust the server-side processing logic in the Python code based on the specific requirements.

28
10. Testing:

• Test with different input values to observe how the server processes and displays results
dynamically.

Expected Outcomes:

29
Result:
Upon completion of the steps, you will have a running Flask web application that
accepts user input, sends it to the server for processing, and displays the result on the
same page. The application provides a foundation for implementing server-side
interactions and dynamic content updates based on user input.

30

You might also like