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

Python Practicals Set-1 & Set-2

The document is a laboratory manual for the Programming in Python with Full Stack Development course at Parul University, detailing various programming exercises and projects. It includes a certificate of completion for a student named Mahek K Surti and outlines practical assignments covering topics such as temperature conversion, area calculation, password generation, and web application development. The manual serves as a guide for students to complete their lab experiments during the academic year 2024/25.

Uploaded by

doingwork42
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 views58 pages

Python Practicals Set-1 & Set-2

The document is a laboratory manual for the Programming in Python with Full Stack Development course at Parul University, detailing various programming exercises and projects. It includes a certificate of completion for a student named Mahek K Surti and outlines practical assignments covering topics such as temperature conversion, area calculation, password generation, and web application development. The manual serves as a guide for students to complete their lab experiments during the academic year 2024/25.

Uploaded by

doingwork42
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/ 58

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY

Programming in Python with Full Stack Development Laboratory


(303105258)

4th Semester
Computer Science & Engineering Department

Laboratory Manual
CERTIFICATE

This is to certify that Ms. MAHEK K SURTI

with enrolment no. 2403031057133 has successfully

completed his laboratory experiments in

Programming in python with full stack development Laboratory

during the academic year 2024/25.

Date: Signature of lab teacher:

Signature of HOD:
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

INDEX

SR. PAGE PERFORMANCE ASSESSMENT


TITLE MARKS SIGN.
NO. NO. DATE DATE
Set-1
1. A program that converts
temperatures from
Fahrenheit to Celsius and
vice versa.
2. A program that calculates
the area and perimeter of a
rectangle.
3. A program that generates a
random password of a
specified length.
4. A program that calculates
the average of a list of
numbers.
1 5. A program that checks if a
given year is a leap year.
6. A program that calculates
the factorial of a number.
7. A program that checks if a
given string is a palindrome.
8. A program that sorts a list of
numbersin ascending or
descending order.
9. A program that generates a
multiplication table for a
given number.
A program that converts a given
number from one base to another.
Set-2
1. A program that models
a bank account, with classes for
the account, the customer, and
the bank.
2. A program that
2 simulatesa school management
system, with classes for the
students, the teachers, and the
courses.
3. A program that reads a
text file and counts the number
of words in it.

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
4. A program that reads a
CSV file and calculates the
average of the values in a
specifiedcolumn.
A programthat reads an Excel file
and prints the data in a tabular
format.

Set-3
1. A program that creates a
simple web server and serves
a static HTML page.
2. A program that creates a web
application that allows users
to register and login.
3. A program that creates a web
application that allows users
3 to upload and download files.
4. A program that creates a web
application that displays data
from a database in a tabular
format.
5. A program that creates a web
application that accepts user
input and sends it to a server-
side script for processing.

Set-4
1. A program that creates a web
application that uses a
template engine to generate
dynamic HTML pages.
2. A program that creates a web
application that supports AJAX
requests and updates the page
without reloading.
3. A program that creates a web
application that uses Django's
4 built-in debugging features to
troubleshoot errors and
exceptions.
4. A program that creates a web
application that implements
user authentication and
authorization.
5. A program that creates a web
application that integrates
with third-party APIs to
provide additional
functionality.

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
Set-5
1. A program that creates a
simple RESTful API that returns
a list of users in JSON format.
2. A program that creates a
RESTful API that allows users
to create, read, update, and
delete resources.
3. A program that creates a
5 RESTful API that authenticates
users using a JSON Web Token.
4. A program that creates a
RESTful API that paginates the
results of a query to improve
performance.
5. A program that creates a
RESTful API that supports data
validation and error handling.

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

PRACTICAL : 1
SET : 1
1. AIM: A program that converts temperatures from Fahrenheit to Celsius and vice
versa.

print("Temperature Conversion Program")

print("1. Convert Fahrenheit to Celsuis")

print("2. Convert Celsius to Fahrenheit")

choice=input("Enter your choice(1 or 2)")

if choice=="1":

Fahrenheit=float(input("Enter temperature in Fahrenheit:"))


Celsuis=(fahrenheit-32)*5/9

print(f("fahrenheit)F is equal to{celsuis:2f} C"))

elif choice=="2":
celsuis=float(input("Enter temperature in celsuis:"))

fahrenheit=(celsuis*9/5)+32

print(f"(celsuis)C is equal to{fahrenheit:2f} F")

else:

print("Invalid choice.Please enter 1 or 2.")

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

2. AIM: A program that calculates the area and perimeter of a rectangle.

lenght=float(input("Enter the length of a rectangle:"))

width=float(input("Enter the width of the rectangle:"))

area=length*width

perimeter=2*(length+width)

print(f"Area of the rectangle:{area:2f}")

print(f"Perimeter of the rectangle:{perimeter:2f}")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

3. AIM: A program that generates a random password of a specified length.

import random
import string

def generate_password(length):

letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation

if length < 4:
return "Password length should be at least 4 to ensure complexity."
else:
password = [
random.choice(letters),
random.choice(digits),
random.choice(special_chars)
]

all_chars = letters + digits + special_chars

passwords = []
passwords += random.choices(all_chars, k=length - 3)
random.shuffle(password)
return ''.join(password)

try:
length = int(input("Enter the desired password length:"))
print(f"Generated Password: {generate_password(length)}")
except ValueError:
print("Please enter a valid number.")

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

4. Aim: A program that calculates the average of a list of numbers.

def calculate_average(numbers):
if not numbers:
return"The list is empty. Cannot calculate the average."

total = sum(numbers)
count = len(numbers)
average = total/count
return average

try:
numbers = list(map(float, input("Enter the numbers separated by spaces:").split()))
average = calculate_average(numbers)
print(f"The average is: {average}")

except ValueError:
print("Please enter valid numbers.")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

5. Aim: A program that checks if a given year is a leap year.

def is_leap_year(year):
if(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True

else:
return False
try:
year = int(input("Enter a year:"))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
except ValueError:
print("Please enter a valid year.")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

6. Aim: A program that calculates the factorial of a number.

def factorial(n):
if n<0:

return"Factorial is not defined for negative numbers."


elif n == 0 or n == 1:
return 1
else:
return n* factorial(n-1)
try:
number = int(input("Enter a non-negative integer:"))
result = factorial(number)
print(f"The factorial of {number} is: {result}")
except ValueError:
print("Please enter a valid non-negative integer.")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

7. Aim: A program that checks if a given string is a palindrome.

string = input("Enter a string:")


string = string.replace("","").lower()

if string == string[::-1]:

print(f'"{string}" is a palidrome.')

else:

print(f'"{string}" is not a palidrome.')

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

8. Aim: A program that sorts a list of numbers in ascending or descending order.

numbers = input("Enter a list of numbers separated by spaces:")


numbers = [int(num)for num in numbers.split()]

print("Choose sorting order.")


print("1. Ascending")
print("2. Descending")

choice = input("Enter your choice(1 or 2):")


if choice == "1":

numbers.sort()
print("Numbers sorted in ascending order.", numbers)
elif choice == "2":
numbers.sort(reverse = True)
print("Numbers sorted in descending order.", numbers)
else:

print("Invalid choice: Please enter 1 or 2.")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

9. Aim: A program that generates a multiplication table for a given number.

number = int(input("Enter the number up to which you want the table: "))

upto = int(input("Enter the range:"))


print(f"\n Multiplication Table for {number}:")

for i in range(1, upto+1):


print(f"{number} x {i} = {number * i}")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

10. Aim: A program that converts a given number from one base to another.

def to_decimal(number,base):
return int(str(number),base)

def from_decimal(number,base):
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
while number > 0:
result = digits[number % base] + result
number = number // base
return result or "0"

number = input("Enter the number:").strip()


source_base = int(input("Enter the source base(2-36):"))
target_base = int(input("Enter the target base(2-36):"))
if source_base < 2 or target_base > 36:
print("Source base must be between 2 and 36.")
elif target_base < 2 or target_base > 36:
print("Target base must be between 2 and 36.")
try:
decimal_value = to_decimal(number, source_base)

result = from_decimal(decimal_value, target_base)

print(f"{number} in base {source_base} is {result} in base {target_base}.")

except ValueError:

print("Invalid number for the specified base.")

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

PRACTICAL : 2
SET : 2

1. AIM: A program that models a bank account, with classes for the account, the customer,
and the bank.

class Account:
def init (self, account_number, balance=0):
self.account_number = account_number
self.balance = balance

def deposit(self, amount):


if amount > 0:
self.balance += amount
print(f"Deposited: {amount}. New balance: {self.balance}")
else:
print("Invalid deposit amount.")

def withdraw(self, amount):


if 0 < amount <= self.balance:
self.balance -= amount
print(f'Withdrawn: {amount}. New balance: {self.balance}')
else:
print("Invalid withdrawal amount or insufficient funds.")

def get_balance(self):
return self.balance
class Customer:
def init (self, name, customer_id):
self.name = name
self.customer_id = customer_id
self.accounts = []

def add_account(self, account):


self.accounts.append(account)
print(f'Account {account.account_number} added for customer {self.name}.')

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

def list_accounts(self):
for account in self.accounts:
print(f'Account Number: {account.account_number}, Balance: {account.balance}')
class Bank:
def init (self, name):
self.name = name
self.customers = []

def add_customer(self, customer):


self.customers.append(customer)
print(f'Customer {customer.name} added to {self.name}.')

def list_customers(self):
print(f"Customers of {self.name}:")
for customer in self.customers:
print(f"Name: {customer.name}, Customer ID: {customer.customer_id}")

if name == " main ":


my_bank = Bank("KRISHNA BANK")
customer1 = Customer("Mahek", "24UG030027")
customer2 = Customer("Disha", "24UG030398")
my_bank.add_customer(customer1)
my_bank.add_customer(customer2)

account1 = Account("A101", 100000)


account2 = Account("A102", 500050)

customer1.add_account(account1)
customer2.add_account(account2)

print("\n-- Banking Operations --")


account1.deposit(200)
account1.withdraw(300)
print(f"Alice's account balance: {account1.get_balance()}")
account2.deposit(100)
account2.withdraw(700)

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

print("\n-- Bank Details --")


my_bank.list_customers()

print("\n-- Customer Accounts --")


customer1.list_accounts()
customer2.list_accounts()

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

2. Aim: A program that simulates a school management system, with classes for the
students, the teachers, and the courses.

class Student:
def init (self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []

def enroll(self, course):


self.courses.append(course)
print(f"Student {self.name} enrolled in {course.name}.")

def list_courses(self):
print(f"Courses for {self.name}:")
for course in self.courses:
print(f" - {course.name} (Code: {course.course_code})")
class Teacher:
def init (self, name, teacher_id):
self.name = name
self.teacher_id = teacher_id
self.courses = []
def assign_course(self, course):
self.courses.append(course)
print(f"Teacher {self.name} assigned to course {course.name}.")
def list_courses(self):
print(f"Courses taught by {self.name}:")
for course in self.courses:
print(f" - {course.name} (Code: {course.course_code})")
class Course:
def init (self, name, course_code):
self.name = name
self.course_code = course_code
self.students = []
self.teacher = None
def assign_teacher(self, teacher):
self.teacher = teacher
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

print(f"Course {self.name} assigned to teacher {teacher.name}.")


def enroll_student(self, student):
self.students.append(student)
print(f"Student {student.name} enrolled in course {self.name}.")
def list_details(self):
print(f"Course: {self.name} (Code: {self.course_code})")
print(f"Teacher: {self.teacher.name if self.teacher else 'None assigned'}")
print("Students:")
for student in self.students:
print(f" - {student.name}")
if name == " main ":
student1 = Student("Mahek", "S001")
student2 = Student("Disha", "S002")

teacher1 = Teacher("Dr. Siddhi", "T001")


teacher2 = Teacher("Ms. Pooja", "T002")

course1 = Course("Mathematics", "MATH101")


course2 = Course("Science", "SCI102")

course1.assign_teacher(teacher1)
course2.assign_teacher(teacher2)

teacher1.assign_course(course1)
teacher2.assign_course(course2)

course1.enroll_student(student1)
course2.enroll_student(student2)

student1.enroll(course1)
student2.enroll(course2)

print("\n-- Course Details --")


course1.list_details()
course2.list_details()
print("\n-- Teacher Details --")
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

teacher1.list_courses()
teacher2.list_courses()
print("\n-- Student Details --")
student1.list_courses()
student2.list_courses()

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

3. Aim: A program that reads a text file and counts the number of words in it.

file_name = input("Enter the file name:")

try:

with open(file_name, 'r') as file:

content = file.read()

words = content.split()

word_count = len(words)

print(f"The file '{file_name}' contains {word_count} words.")

except FileNotFoundError:

print(f"The file '{file_name}' was not found. Please check the file try again.")

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
4. Aim: A program that reads a CSV file and calculates the average of the values in a
specified column. A program that reads an Excel file and prints the data in a tabular
format.

import csv

file_name = input("Enter the CSV file name:")

column_name = input("Enter the column name to calculate the averge:")

try:

with open(file_name, 'r') as csv_file:


csv_reader = csv.DictReader(csv_file)

total = 0

count = 0
for row in csv_reader:

try:

total += float(row[column_name])
count += 1
except ValueError:

print(f"Skipping invalid data: {row[column_name]}")

except KeyError:

print(f"Column '{column_name}' not found in the file.")

break

if count > 0:

average = total / count


print(f"The average of the '{column_name}' column is: {average}")

else:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

print(f"No valid data found in column '{column_name}'.")

except FileNotFoundError:

print(f"The file '{file_name}' was not found. Please check the file name and try again.")

Output:

2403031057133 (MAHEK SURTI)


Faculty of Engineering & Technology
Subject Name : Programming in
Python with Full Stack Development
Subject Code : 303105258
B.Tech CSE Year 2nd Semester 4th

5. Aim : A program that reads an Excel file and prints the data in a tabular format.

Source Code:
import pandas as pd
file_name = r'./jay.xlsx'

try:
data = pd.read_excel(file_name,engine='openpyxl')
print("\nData in the Excel file:")
print(data.to_markdown(index=False))
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except PermissionError:
print(f"Permission denied to open '{file_name}'.")

Output:

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

PRACTICAL : 3
SET : 3
1. Aim : A program that creates a simple web server and serves a static HTML page.
Python code:

from http.server import HTTPServer, SimpleHTTPRequestHandler


HOST = "localhost"
PORT = 8000
class staticserver(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
return super().do_GET()
def run_server():
with HTTPServer((HOST, PORT), StaticServer) as server:
print(f"Serving on http://{HOST}:{PORT}")
server.serve_forever()
if name == "_main_":
run_server()

HTML CODE :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Web Server</title>
</head>
<body>
<h1>Welcome to My Simple Web Server!</h1>
<p>This is a static HTML page served by a Python web server.</p>
</body>
</html>

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

Output :

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

2. Aim: A program that creates a web application that allows users to register and login.

Python Code:
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
app = Flask( name )
app.secret_key = 'your_secret_key'
# Database setup
def init_db():
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
''')
conn.commit()
conn.close()
@app.route("/")
def home():
return render_template('home.html')

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]

conn = sqlite3.connect('users.db')
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username,
password))
conn.commit()
flash("Registration successful! Please log in.", "success")
return redirect(url_for("login"))
except sqlite3.IntegrityError:
flash("Username already exists. Please choose a different one.", "error")
finally:
conn.close()
return render_template("signup.html")

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


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

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?",
(username, password))
user = cursor.fetchone()
conn.close()
if user:
flash("Login successful!", "success")
return redirect(url_for("home"))
else:
flash("Invalid username or password. Please try again.", "error")
return render_template("signin.html")
if name == " main ":
init_db()
app.run(debug=True)

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
HTML Code:
HTML Home:

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to the web Application</h1>
<a href="/register">Register</a> | <a href="/login">Login</a>
</body>
</html>

HTML Register:

<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
<p style="color: {{ 'red' if category == 'error' else 'green' }}">{{ message }}</p>
{% endfor %}
{% endwith %}
<form method= "POST">
<label>Username: </label><br>
<input type="text" name= "username" required><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<button type="submit">Register</button>
</form>
<a href="/">Home</a>
</body>
</html>

HTML Login:

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}

2403031057109 (DISHA RATHOD)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
<p style="color: {{ 'red' if category == 'error' else 'green' }}">{{ message }}</p>
{% endfor %}
{% endwith %}
<form method= "POST">
<label>Username:</label><br>
<input type="text" name="username" required><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<a href="/">Home</a>
</body>
</html>

HTML Dashborad:
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Welcome, {{ username }}</h1>
<a href="/logout">Logout</a>
</body>
</html>

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
Output :

Home Page:

Login Page: (Sign in Page)

Login Page: (Sign up Page)

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

3. Aim: A program that creates a web application that allows users to upload and download
files.

Python Code:

from flask import Flask, request, redirect, url_for, send_from_directory, render_template


import os

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

files = os.listdir(app.config['UPLOAD_FOLDER']) return render_template('index.html',


files=files)

if 'file' not in request.files: return "No file part", 400

file = request.files['file'] if file.filename == '':


return "No selected file", 400

if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(filepath)
return redirect(url_for('home'))

return send_from_directory(app.config['UPLOAD_FOLDER'], filename,


as_attachment=True)

if name == ' main ': app.run(debug=True)

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
HTML Code:

<!doctype html>
<html>
<head>
<title>File Upload and Download</title>
</head>
<body>
<h1>Upload and Download Files</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<h2>Files:</h2>
<ul>
{% for file in files %}
<li><a href="{{ url_for('download_file', filename=file) }}">{{ file }}</a></li>
{% endfor %}
</ul>
</body>
</html>

Output :

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

4. Aim: A program that creates a web application that displays data from a database in a
tabular format.

Python Code:

from flask import Flask, render_template import sqlite3

app = Flask( name )

# Database file DATABASE = "data.db"

# Function to initialize the database def init_db():


with sqlite3.connect(DATABASE) as conn: cursor = conn.cursor()

# Create a sample table if it doesn't exist cursor.execute("""


CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL,
position TEXT NOT NULL, salary REAL NOT NULL
) """)
# Insert sample data if the table is empty cursor.execute("SELECT COUNT(*) FROM
employees") if cursor.fetchone()[0] == 0:
sample_data = [
("Alice", "Software Engineer", 75000), ("Bob", "Data Analyst", 65000), ("Charlie", "Project
Manager", 85000),
]
cursor.executemany("INSERT INTO employees (name, position, salary) VALUES (?, ?,
?)", sample_data) conn.commit()

# Route to display data in a tabular format @app.route("/")


def index():
with sqlite3.connect(DATABASE) as conn: cursor = conn.cursor() cursor.execute("SELECT *
FROM employees")
employees = cursor.fetchall() # Fetch all rows from the table return
render_template("table.html", employees=employees)

if name == " main ": init_db() # Initialize the database app.run(debug=True)

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Table</title>
<style>
table {
width: 80%; margin: 20px auto;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd; padding: 10px;
text-align: center;
}
th {
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Employee Data</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee[0] }}</td>
<td>{{ employee[1] }}</td>
<td>{{ employee[2] }}</td>

<td>${{ employee[3] }}</td>


</tr>
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
{% endfor %}
</tbody>
</table>
</body>
</html>

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

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

Python Code:

from flask import Flask, render_template, request app = Flask( name )

# Route for the home page with the input form @app.route("/", methods=["GET",
"POST"]) def index():
if request.method == "POST":

# Get user input from the form user_input = request.form["user_input"]

# Process the input (in this case, reverse the string) processed_data = user_input[::-1]

# Pass the processed data to the result template


return render_template("result.html", original=user_input, result=processed_data)

# Render the form on GET request return render_template("input.html")

if name == " main ": app.run

HTML Code:

Input.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 Form</title>
</head>
<body>
<h1>Enter a String</h1>
<form method="POST">
<label for="user_input">Your Input:</label>
<input type="text" id="user_input" name="user_input" required>
<button type="submit">Submit</button>
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
</form>
</body>
</html>

Result.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Processed Result</title>
</head>
<body>
<h1>Processed Result</h1>
<p><strong>Original Input:</strong> {{ original }}</p>
<p><strong>Processed Output:</strong> {{ result }}</p>
<a href="/">Go Back</a>
</body>
</html>

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
PRACTICAL : 4
SET : 4

1. Aim: A program that creates a web application that uses a template engine to generate
dynamicHTML pages.

Python Code:

from flask import Flask, render_template app = Flask( name )


@app.route("/") def home():
# Data to be passed to the template items = [
{"name": "Apple", "price": "$1.00"},
{"name": "Banana", "price": "$0.50"},
{"name": "Cherry", "price": "$2.00"},
{"name": "Date", "price": "$3.00"},
{"name": "Elderberry", "price": "$4.50"},
]

# Render the template with dynamic data


return render_template("dynamic.html", items=items)

if name == " main ": app.run(debug=True)

HTML Code:
from flask import Flask, render_template app = Flask( name )
@app.route("/") def home():
# Data to be passed to the template items = [
{"name": "Apple", "price": "$1.00"},
{"name": "Banana", "price": "$0.50"},
{"name": "Cherry", "price": "$2.00"},
{"name": "Date", "price": "$3.00"},
{"name": "Elderberry", "price": "$4.50"},
]

return render_template("dynamic.html", items=items)

if name == " main ": app.run(debug=True)


2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

2. Aim: A program that creates a web application that supports AJAX requests and updates
the page without reloading.

ajax_app/
├── app.py # Flask application
├── static/ │ └── script.js # JavaScript for handling AJAX
├── templates/ │ ├── index.html # Main HTML file app.py
from flask import Flask, render_template, request, jsonify app = Flask( name )
# Data storage (simulating a database) items = []

@app.route("/") def home():


return render_template("index.html")

@app.route("/add_item", methods=["POST"]) def add_item():


new_item = request.json.get("item") # Get data from the AJAX request if new_item:
items.append(new_item) # Add the new item to the list
return jsonify({"success": True, "items": items}) # Return updated list return
jsonify({"success": False, "error": "No item provided"})

if name == " main ": app.run(debug=True)

script.js
$(document).ready(function () {
$("#add-item-form").on("submit", function (e) { e.preventDefault(); // Prevent form from
reloading the page
const newItem = $("#item-input").val().trim(); if (newItem) {
$.ajax({
url: "/add_item", type: "POST",
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
contentType: "application/json",
data: JSON.stringify({ item: newItem }), success: function (response) {

if (response.success) { updateList(response.items);
$("#item-input").val(""); // Clear input field
} else {
alert(response.error || "An error occurred.");
}
},
error: function () {
alert("Failed to communicate with the server.");
},
});
} else {
alert("Please enter an item.");
}
});

function updateList(items) { const list = $("#item-list");


list.empty(); // Clear existing list items.forEach((item) => {
list.append(`<li>${item}</li>`);
});
}
});

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif; margin: 20px;
}
h1 {
text-align: center;
}
form {
text-align: center; margin-bottom: 20px;
}
ul {
list-style-type: none; padding: 0;
}
li {
margin: 5px 0;
}
</style>

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
</head>
<body>
<h1>AJAX Item List</h1>
<form id="add-item-form">
<input type="text" id="item-input" placeholder="Enter an item" required>
<button type="submit">Add Item</button>
</form>
<ul id="item-list">
<!-- Dynamically updated list -->
</ul>
<script src="/static/script.js"></script>
</body>
</html>

Output:

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

3. Aim: A program that creates a web application that uses Django's built-in debugging
features to troubleshoot errors and exceptions.

Steps:
1. Install Django (if not installed)
pip install django

2. Create a Django Project


django-admin startproject debug_project cd debug_project

3. Create a Django App


python manage.py startapp debug_app

4. Enable Debug Mode in settings.py


Make sure DEBUG = True in debug_project/settings.py: DEBUG = True
ALLOWED_HOSTS = []

5. Create a View with Intentional Errors


from django.http import HttpResponse

def trigger_error(request):
"""This function intentionally triggers an error to test debugging.""" x = 1 / 0 # This will
cause a ZeroDivisionError
return HttpResponse("This will never be reached.")

6. Configure URLs
Edit debug_app/urls.py:
from django.urls import path from .views import trigger_error urlpatterns = [

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
path('error/', trigger_error, name='trigger_error'),
]
Now, link the app's URLs to debug_project/urls.py: from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('debug_app.urls')), # Include debug_app URLs
]

7. Run the Server & Test Debugging


Run the Django development server:
python manage.py runserver http://127.0.0.1:8000/error/
Expected Output: Django will display a detailed error page showing:
Error Type: ZeroDivisionError Line Number & Code Snippet
Request Info (GET, POST, Headers, etc.) Traceback for Debugging

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR

4. Aim: A program that creates a web application that implements user authentication
and authorization.

Steps:
1. Install Django pip install django
2. Create a Django Project
django-admin startproject auth_project cd auth_project
3. Create an App
python manage.py startapp accounts
4. Configure urls.py
Edit auth_project/urls.py:
from django.contrib import admin from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')), # Include authentication routes
]
5. Create User Authentication Views
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate from
django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == "POST":
username = request.POST['username'] password = request.POST['password']
confirm_password = request.POST['confirm_password']
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
if password != confirm_password: messages.error(request, "Passwords do not match!")
return redirect('register')
if User.objects.filter(username=username).exists(): messages.error(request, "Username
already exists!") return redirect('register')
user = User.objects.create_user(username=username, password=password) user.save()
messages.success(request, "Registration successful! Please log in.") return redirect('login')
return render(request, "register.html")

def user_login(request):
if request.method == "POST":

username = request.POST['username'] password = request.POST['password']


user = authenticate(request, username=username, password=password)
if user is not None: login(request, user)
return redirect('dashboard') else:
messages.error(request, "Invalid credentials!") return redirect('login')
return render(request, "login.html")

def user_logout(request): logout(request)


return redirect('login')

@login_required
def dashboard(request):
return render(request, "dashboard.html")
6. Set Up URLs Set Up URLs
from django.urls import path
from .views import register, user_login, user_logout, dashboard

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
urlpatterns = [
path('register/', register, name='register'), path('login/', user_login, name='login'),
path('logout/', user_logout, name='logout'),
path('dashboard/', dashboard, name='dashboard'), # Protected route
]
7. Create HTML Templates
<!DOCTYPE html>
<html>
<head><title>Register</title></head>
<body>
<h2>Register</h2>
<form method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="password" name="confirm_password" placeholder="Confirm Password"
required>
<button type="submit">Register</button>
</form>
<a href="{% url 'login' %}">Already have an account? Login</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html>
<head><title>Login</title></head>

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
<body>
<h2>Login</h2>
<form method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
<a href="{% url 'register' %}">Don't have an account? Register</a>
</body>
</html>

dashboard.html (Protected Page)


<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
<body>
<h2>Welcome, {{ user.username }}!</h2>
<p>This is a protected page.</p>
<a href="{% url 'logout' %}">Logout</a>
</body>
</html>
8. Apply Migrations
python manage.py makemigrations

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
python manage.py migrate
9. Run the Server
python manage.py runserver Testing the Application
1 Go to http://127.0.0.1:8000/register/ → Register a user
2 Go to http://127.0.0.1:8000/login/ → Log in
3 Go to http://127.0.0.1:8000/dashboard/ → Dashboard (only accessible when logged in)
4 Logout & Try Dashboard Again → Redirected to login

2403031057133 (MAHEK SURTI)


PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
PRACTICAL : 5
SET : 5

1. Aim: A program that creates a simple RESTful API that returns a list of users in JSON
format.

Step1: pip install fastapi uvicorn


Step 2: main.pys
from fastapi import FastAPI

app = FastAPI()

@app.get("/") def read_root():


return {"message": "Hello, World!"} Step 3: python -m uvicorn main:app –reload Then
visit: http://127.0.0.1:8000

Output:

2403031057133 (MAHEK SURTI)

You might also like