0% found this document useful (0 votes)
7 views83 pages

Python

This document is a laboratory manual for a Bachelor of Technology program in Programming in Python with Full Stack Development, detailing various programming experiments for the Computer Science & Engineering Department. It includes a certificate of completion for a student, a table of contents listing different programming tasks, and sample codes for each task. The tasks range from basic programming exercises to more complex web application development and RESTful API creation.

Uploaded by

pathankhushi09
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)
7 views83 pages

Python

This document is a laboratory manual for a Bachelor of Technology program in Programming in Python with Full Stack Development, detailing various programming experiments for the Computer Science & Engineering Department. It includes a certificate of completion for a student, a table of contents listing different programming tasks, and sample codes for each task. The tasks range from basic programming exercises to more complex web application development and RESTful API creation.

Uploaded by

pathankhushi09
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

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY

PROGRAMMING IN PYHTON WITH


FULL STACK DEVELOPMENT LABORATORY
(303105258)

IV SEMESTER

Computer Science & Engineering Department

Laboratory Manual
Session 2025-26
CERTIFICATE

This is to certify that Ms. Khushbu Pathan with enrollment no

2503031057167 has successfully completed his laboratory experiments in

the PPFSD-LAB (303105258) from the department of COMPUTER

SCIENCE & ENGINEERING during the academic year 2025-2026.

Date of Submission:......................... Staff In charge:...........................

Head Of Department:...........................................
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
CN (303105256) B. Tech.4TH SEM
ENROLLMENT NO: 2303051050377

TABLE OF CONTENT

Page No
Sr. Date of Date of Marks
Experiment Title Sign
No Start Completion (out of 10)
From To

SET-1
A program that converts
1. temperatures from Fahrenheit 01 01
to Celsius and vice versa.
2. A program that calculates the
area and perimeter of a rectangle. 02 02
A program that generates a
3. random password of a specified 03 03
length.
A program that calculates
4. the average of a list of 04 04
numbers.
5. Aprogramthat checks if a given
year is a leap year. 05 05

6. A program that calculates the


factorial of a number. 06 06

7. A program that checks if a given


string is a palindrome 07 07
A program that sorts a list of
8. numbers in ascending or 08 08
descending order.
A program that generates a
9. multiplication table for a given 09 09
number.
A program that converts a
10. given number from one base to 10 12
another.
SET-2
A program that models a bank
11. account, with classes for the
account, the customer, and the 13 17
bank.
A program that simulates a
12. school management system,
with classes for the students, 18 20
the teachers, and the courses.
A program that reads a text file
13. and counts the number of 21 21
words in it.
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
CN (303105256) B. Tech.4TH SEM
ENROLLMENT NO: 2303051050377

A program that reads a CSV


14. file and calculates the average
of the values in a specified 22 23
column.
A program that reads an Excel
15. file and prints the data in a 24 24
tabular format.

SET-3
A program that creates a simple
16. web server and serves a static 25 26
HTML page.
A program that creates a web
17. application that allows users to 27 36
register and login.
A program that creates a web
18. application that allows users to 37 38
upload and download files
A program that creates a web
19. application that displays data
from a database in a tabular 39 41
format.
A program that creates a web
20. application that accepts user
input and sends it to a server- 42 45
side script for processing.

SET-4
A program that creates a web
21. application that uses a template
engine to generate dynamic 46 47
HTML pages.
A program that creates a web
22. application that supports AJAX
requests and updates the page 48 49
without reloading.
A program that creates a web
application that uses Django's
23. built-in debugging features to 50 52
troubleshoot errors and
exceptions.
A program that creates a web
24. application that implements
user authentication and 53 61
authorization.
A program that creates a web
25. application that integrates with
third-party APIs to provide 62 64
additional functionality.
OMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
CN (303105256) B. Tech.4TH SEM
ENROLLMENT NO: 2303051050377

SET-5
A program that creates a simple
26. RESTful API that returns a list 65 65
of users in JSON format.
A program that creates a
27. RESTful API that allows users
to create, read, update, and 66 68
delete resources.
A program that creates a
28. RESTful API that authenticates
users using a JSON Web 69 70
Token.
A program that creates a
29. RESTful API that paginates the
results of a query to improve 71 72
performance
A program that creates a
30. RESTful API that supports data 73 74
validation and error handling.
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

SET-1
PRACTICAL-1

AIM : A program that converts temperatures from Fahrenheit to Celsius


and vice versa.
CODE:
celsius =int(input("\n"))

fahrenheit = (celsius * 1.8) + 32

print(celsius,"celsius is equal to",fahrenheit, "fahrenheit")

fahrenheit2 =int(input("\n"))

celsius2= (fahrenheit-32)*1.8

print(fahrenheit2,"fahrenheit is equal to",celsius2, "celsius")

 Output:

Enrollment No - 2503031057167 1|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 2

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

CODE:
length=int(input("enter the length\n"))
breadth=int(input("enter the breadth\n"))
Area=length*breadth
Perimeter = 2*(length+breadth)
print("Area",Area)
print("Perimeter",Perimeter)

CODE:

Enrollment No - 2503031057167 2|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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

CODE:

import string
import random
def generate(n):
c=string.ascii_letters +[Link] + [Link]
password=''.join([Link](c) for _ in range(n))
return password
n=int(input("enter the length of the password\n"))
r=generate(n)
print(r)

OUTPUT:

Enrollment No - 2503031057167 3|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 4
AIM: A program that calculates the average of a list of numbers.

CODE:
list=[1,2,4,5,7,8]
average=sum(list)/len(list) print("average
of list elements:",average

 OUTPUT

Enrollment No - 2503031057167 4|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 5

 AIM: A program that checks if a given year is a leap year


 CODE:
year=int(input("\n"))
if year%4==0 and year%100!=0 or year%400==0 :
print(year,"is a leap year")
else:
print(year,"is not a leap year")

OUTPUT:

Enrollment No - 2503031057167 5|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL-6

 AIM: A program that calculates the factorial of a number


 CODE:
h=int(input("\n"))
fact=1
for i in range(1,h+1):
fact=fact*i
print("factor of",h,"is",fact)

OUTPUT:

Enrollment No - 2503031057167 6|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 7

 AIM: A program that checks if a given string is a palindrome


 CODE:
def isPalindrome(s):
return s == s[::-1]
s = "car"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

OUTPUT:

Enrollment No - 2503031057167 7|Page


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
PRACTICAL- 8

 AIM: A program that sorts a list of numbers in ascending or


descending order
 CODE:
def sort():
if order=="A":
Sl=sorted(list1)
elif order=="D":
Sl=sorted(list1,reverse=True)
else:
print("involid")
return
print(Sl)
list1=input("enter the list elements\n").split()
list1=[int(n) for n in list1]
order=input("A or D\n")
sort()

OUTPUT:

Enrollment No - 2503031057167 8|Pa ge


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 9

 AIM: A program that generates a multiplication table for a given


number.
 CODE:
n = int(input("Enter a number: "))
for i in range(1,11):
print(f"{n} x {i} = {n*i}")

OUTPUT:

Enrollment No - 2503031057167 9|Pa ge


Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 10

 AIM: A program that converts a given number from one base to


another.
 CODE:
def decimal_others(value,choice):
if choice==1:
return value
elif choice==2:
return '{0:b}'.format(value)
elif choice==3:
return '{0:o}'.format(value)
elif choice==4:
return '{0:x}'.format(value)
else:
return "Invalid Option"
def binary_others(value,choice):
if choice==1:
return value
elif choice==2:
return int(value,2)
elif choice==3:
return '{0:o}'.format(int(value,2))
elif choice==4:
return '{0:x}'.format(int(value,2))
else:
return "Invalid Option"
def octal_others(value,choice):
if choice==1:
return value
elif choice==2:
return int(value,8)
elif choice==3:
return '{0:b}'.format(int(value,8))
elif choice==4:
return '{0:x}'.format(int(value,8))
else:

Enrollment No - 2503031057167 10 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

return "Invalid Option"


def hex_others(value,choice):
if choice==1:
return value
elif choice==2:
return int(value,16)
elif choice==3:
return '{0:0}'.format(int(value,16))
elif choice==4:
return '{0:b}'.format(int(value,16))
else:
return "Invalid Option"
print("Convert from: 1: decimal ,2: binary,3: octal 4:hexadecimal")
input_choice=int(input("Enter the choice"))
if input_choice==1:
decimal_num=int(input("Enter decimal number"))
print('Convert to: 1: decimal ,2: binary,3: octal 4:hexadecimal')
choice=int(input("Enter Target conversion:\n"))
print("Converted value: ",decimal_others(decimal_num,choice))
elif input_choice==2:
binary_num=input("Enter decimal number")
print('Convert to: 1: binary ,2: decimal,3: octal 4:hexadecimal')
choice=int(input("Enter Target conversion:\n"))
print("Converted value: ",binary_others(binary_num,choice))
elif input_choice==3:
octal_num=input("Enter decimal number")
print('Convert to: 1: octal ,2: decimal,3: binary 4:hexadecimal')
choice=int(input("Enter Target conversion:\n"))
print("Converted value: ",octal_others(octal_num,choice))
elif input_choice==4:
hex_num=input("Enter decimal number")
print('Convert to: 1: hex,2: decimal,3: octal 4:binary')
choice=int(input("Enter Target conversion:\n"))
print("Converted value: ",hex_others(hex_num,choice))

Enrollment No - 2503031057167 11 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

OUTPUT:

Enrollment No - 2503031057167 12 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

SET-2
PRACTICAL-1

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

CODE:
import random
class Customer:
def init (self, name, address, contact_number):
[Link] = name [Link] = address
self.contact_number = contact_number [Link] = []

def create_account(self, account_type, initial_balance):


account_number = Bank.generate_account_number()
account = BankAccount(account_type, initial_balance, self, account_number)
[Link](account)
return account
def display_customer_info(self):
print(f"Customer Name: {[Link]}")

print(f"Address: {[Link]}")
print(f"Contact Number: {self.contact_number}") print("Accounts:")
for account in [Link]:
print(f" - {account}")

class BankAccount:
def init (self, account_type, balance, owner, account_number):
self.account_type = account_type
self. Balance = balance [Link] = owner

Enrollment No - 2503031057167 13 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
self.account_number = account_number

def deposit(self, amount):


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

def withdraw(self, amount):


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

def str (self):


return f"{self.account_type} Account - Account Number: {self.account_number}, Balance: INR
{[Link]}"
class Bank:
def init (self, name):
[Link] = name [Link] = []

def add_customer(self, customer): [Link](customer)

@staticmethod
def generate_account_number():
return ''.join([Link]('0123456789') for _ in range(8))
def display_bank_info(self):
print(f"Bank Name: {[Link]}") print("Customers:")
for customer in [Link]: customer.display_customer_info() print()
def find_account_by_number(self, account_number): for customer in [Link]:
for account in [Link]:

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

# Example usage

Enrollment No - 2503031057167 14 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
if name == " main ": # Create a bank
my_bank = Bank("My Bank") customer_list=[]
while True:
print("1. New Customer 2. Existing Customer 3. Find Customers info [Link]") try:
choice = int(input())

if choice==1:
print("Customer Registration: \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 option...Try again")

if choice==2:
# User input for transactions
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.[Link]}!") 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")
option=int(input("Enter your Option:\n"))

Enrollment No - 2503031057167 15 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

if option==1:
print("Welcome to Deposit Section\n") # Deposit
deposit_amount = int(input("\nEnter the amount to deposit: INR "))
account_to_transact.deposit(deposit_amount)
elif option==2:
print("Welcome to withdrawl section:\n") # Withdrawal
withdrawal_amount = int(input("\nEnter the amount to withdraw: INR "))
account_to_transact.withdraw(withdrawal_amount)
elif option==3:
# Display updated account information print("\nUpdated Account Information:") print(account_to_transact)
elif option==4: break
else:
print("Invalid Option")
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 option.")
continue

Enrollment No - 2503031057167 16 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

OUTPUT:

Enrollment No - 2503031057167 17 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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

CODE:
class Student:
def init (self, student_id, name, grade):
self.student_id = student_id
[Link] = name [Link] = grade
def display_info(self):
print(f"\nStudent ID: {self.student_id}, Name: {[Link]}, Grade: {[Link]}")
class Teacher:
def init (self, teacher_id, name, subject):
self.teacher_id = teacher_id [Link] = name [Link] = subject
def display_info(self):
print(f"\nTeacher ID: {self.teacher_id}, Name: {[Link]}, Subject: {[Link]}")

class Course:
def init (self, course_code, course_name, teacher, students):
self.course_code = course_code
self.course_name = course_name [Link] = teacher [Link] = students
def display_info(self):
print(f"\nCourse Code: {self.course_code}, Course Name: {self.course_name}")
print("\nTeacher:")
[Link].display_info() print("\nStudents:")
for student in [Link]: student.display_info()
def main():
students = []

Enrollment No - 2503031057167 18 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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: ")
[Link](Student(student_id, name, grade)) print("\nRegistration 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: ")
[Link](Teacher(teacher_id, name, subject))

print("\nRegistration 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(",")

Enrollment No - 2503031057167 19 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
students_for_course = [students[int(index)] for index in student_indices]
[Link](Course(course_code, course_name, teacher, students_for_course))
print("\nRegistration successful.")
else:
print("\nInvalid input")
if name == " main ":
main()

OUTPUT:

Enrollment No - 2503031057167 20 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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

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

OUTPUT:

Enrollment No - 2503031057167 21 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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

CODE:
import csv
def calculate_average(csv_file, column_name): try:
with open(csv_file, 'r') as file:
reader = [Link](file)
if column_name not in [Link]:
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}'.")
return None average = total / count return average
except FileNotFoundError:
print(f"File '{csv_file}' not found.") return None
csv_file_path = '[Link]' 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}")

Enrollment No - 2503031057167 22 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

 OUTPUT:

Enrollment No - 2503031057167 23 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

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

CODE:
import pandas as pd import openpyxl
output = pd.read_excel("[Link]") print(output)

OUTPUT:

Enrollment No - 2503031057167 24 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

SET-3
PRACTICAL-1
AIM : A program that creates a simple web server and serves a static
HTMLpage.

CODE:

 [Link]

<!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>

Enrollment No - 2503031057167 25 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 [Link]

from flask import Flask, render_template

app = Flask( name )

@[Link]("/")

def home():

return render_template("[Link]")

if name == " main ":

[Link](debug=True)

Actual Output:

Enrollment No - 2503031057167 26 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 2
AIM: A program that creates a web application that allows users to
registerand login.

CODE:

 [Link]
<!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("[Link]
*{
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;
Enrollment No - 2503031057167 27 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

font-weight: 300;
transition: .3s;
&:hover{ backgr
ound: #fff; color:
#000; cursor:
pointer;
}
}
</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>

 [Link]
<!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;

Enrollment No - 2503031057167 28 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

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;
}
& .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{ paddin
g: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& input {

Enrollment No - 2503031057167 29 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

margin: 10px 20px;


}
}
}
.error
{ color:
red;
}
.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>

Enrollment No - 2503031057167 30 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 [Link]
<!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>
*{
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;
}

Enrollment No - 2503031057167 31 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
& 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;
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;
}

Enrollment No - 2503031057167 32 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

.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 %}
<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>

Enrollment No - 2503031057167 33 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

<p>
Already have an account?
<a href="{{ url_for('login') }}">Log in here</a>.
</p>
</div>
</body>
</html>

Enrollment No - 2503031057167 34 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 [Link]
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from [Link] import generate_password_hash, check_password_hash
import secrets

app = Flask( name )


app.secret_key = secrets.token_hex(16)
[Link]['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///[Link]'
db = SQLAlchemy(app)

class User([Link]):
id = [Link]([Link], primary_key=True)
username = [Link]([Link](50), unique=True, nullable=False)
password = [Link]([Link](256), nullable=False)

withapp.app_context():
db.create_all()
@[Link]("/")
def home():

return render_template("[Link]")

@[Link]('/register', methods=['GET', 'POST'])


def register():
if [Link] == 'POST':
username = [Link]['username']
password = [Link]['password']
if [Link].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)
[Link](new_user)
[Link]()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))

return render_template('[Link]')

@[Link]('/login', methods=['GET', 'POST'])


def login():
if [Link] == 'POST':
username = [Link]['username']
password = [Link]['password']

user = [Link].filter_by(username=username).first()

Enrollment No - 2503031057167 35 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

if user and check_password_hash([Link], password):


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

returnrender_template('[Link]')
@[Link]('/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'))

@[Link]('/logout')
def logout():
[Link]('username', None)
flash('You have been logged out.', 'info')
return redirect(url_for('login'))

if name == ' main ':


[Link](debug=True)

Enrollment No - 2503031057167 36 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 Output:

Enrollment No - 2503031057167 37 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

Enrollment No - 2503031057167 38 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 3

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

CODE:

 [Link]
<!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>

 [Link]
from flask import Flask, render_template, request, send_from_directory,
redirect, url_for
import os
app = Flask( name )
UPLOAD_FOLDER = 'uploads'
[Link]['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Enrollment No - 2503031057167 39 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

18

[Link](UPLOAD_FOLDER, exist_ok=True)
@[Link]('/')
def index():
filenames = [Link]([Link]['UPLOAD_FOLDER'])
return render_template('[Link]', filenames=filenames)
@[Link]('/upload', methods=['POST'])
def upload_file():
if 'file' not in [Link]:
return "No file part"
file = [Link]['file']
if [Link] == '':
return "No selected file"
[Link]([Link]([Link]['UPLOAD_FOLDER'], [Link]))
return redirect(url_for('index'))
@[Link]('/download/<filename>')
def download_file(filename):
return send_from_directory([Link]['UPLOAD_FOLDER'], filename)
if name == ' main ':
[Link](debug=True)
 Output:

Enrollment No - 2503031057167 40 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 4

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

CODE:

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Display</title>
<link rel="stylesheet"
href="[Link]
</head>
<body>
<div class="container mt-5">
<h1>Data Display</h1>
<!-- Render the HTML table -->
{{ table_html | safe }}
</div>
</body>
</html>

 [Link]
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import pandas as pd

app = Flask( name ) [Link]['SQLALCHEMY_DATABASE_URI']


= 'sqlite:///[Link]'
[Link]['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create a SQLAlchemy instance


db = SQLAlchemy(app)

Enrollment No - 2503031057167 41 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

# Define a model for the data


class Person([Link]):
id = [Link]([Link], primary_key=True)
name = [Link]([Link](50), nullable=False)
age = [Link]([Link], 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'])
[Link](person)
[Link]()
# Define a route to display data in tabular format
@[Link]('/')
def display_data():
# Query data from the database
data = [Link]()

# Convert the data to a Pandas DataFrame


df = [Link]([([Link], [Link]) 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('[Link]', table_html=table_html)

if name == ' main ':


[Link](debug=True)

Enrollment No - 2503031057167 42 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 Output:

Enrollment No - 2503031057167 43 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

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

CODE:

 [Link]
<!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;

Enrollment No - 2503031057167 44 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

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;
}
& .submit{
padding: 10px 20px;
color: #fff;
background: #2a9d8f;
outline: none;
border: none;
border-radius: 10px;
transition: .3s;
transform: translateX(150px);
margin: 30px;
&:hover{ colo
r: #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 />
Enrollment No - 2503031057167 45 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

<br />
<input class="submit" type="submit" value="Submit" />
</form>

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

 [Link]
from flask import Flask, render_template, request
app = Flask( name )
# Define a route for the main page
@[Link]('/', methods=['GET', 'POST'])
def index():
result = None
if [Link] == 'POST':
# Get user input from the form
user_input = [Link]('user_input')
result = f"You entered: {user_input}"
return render_template('[Link]', result=result)

if name == ' main ':


[Link](debug=True)

Enrollment No - 2503031057167 46 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 Output:

Enrollment No - 2503031057167 47 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

SET-4
PRACTICAL-1

AIM : A program that creates a web application that uses a template engine
to generate dynamic HTML pages.
CODE:

 [Link]

<!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>Flask Template Example</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>

 [Link]

from flask import Flask, render_template


app = Flask( name )

Enrollment No - 2503031057167 48 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

@[Link]("/")def home():

return render_template('[Link]',message='Hello, World!')


if name == " main ":
[Link](debug=True)

Actual Output:

Enrollment No - 2503031057167 49 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 2

AIM: A program that creates a web application that supports AJAX


requests and updates the page without reloading

CODE:

index_ajax.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> Flask AJAX Example </title>
<script>
async function updateMessage() {
const messageInput = [Link]('message');
const message = [Link];
const response = await fetch('/update',
{ method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: [Link]({ 'message': message }),
});
const responseData = await [Link]();
[Link]('output').innerHTML =
[Link];
}
</script>
</head>
<body>

Enrollment No - 2503031057167 50 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

<h1>Flask AJAX Example</h1>

<input type="text" id="message" placeholder="Enter message">


<button onclick="updateMessage()">Update</button>
<div id="output"></div>
</body>
</html>

 [Link]
from flask import Flask, render_template
app = Flask( name )
@[Link]("/")def home():
return render_template('[Link]',message='Hello, World!')
if name == " main ":
[Link](debug=True)

 Output:

Enrollment No - 2503031057167 51 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 3

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

CODE:

[Link]
import os
import sys
if name == " main ":
[Link]("DJANGO_SETTINGS_MODULE", "[Link]")
try:
from [Link] import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did
you "
"forget to activate a virtual environment?"
) from exc
execute from command_line([Link])

[Link]
import os
BASE_DIR = [Link]([Link]([Link]( file )))
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []

Enrollment No - 2503031057167 52 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

INSTALLED_APPS = [
'[Link]',
]
MIDDLEWARE = [
'[Link]',
]
ROOT_URLCONF = '[Link]'
TEMPLATES = [
{
'BACKEND': '[Link]',
'DIRS': [[Link](BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors':
[ '[Link].context_processors.debug',
'[Link].context_processors.request',
'[Link].context_processors.auth',
'[Link].context_processors.messages',
],
},
},
]
WSGI_APPLICATION = '[Link]'
DATABASES = {
'default': {
'ENGINE': '[Link].sqlite3',
'NAME': [Link](BASE_DIR, 'db.sqlite3'),
}
}

Enrollment No - 2503031057167 53 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = '[Link]'

 [Link]
from [Link] import path
from [Link] import HttpResponseServerError
def trigger_error(request):
return HttpResponseServerError("Intentional Error for Debugging")
urlpatterns = [
path('error/', trigger_error),
]

 Output:

Enrollment No - 2503031057167 54 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 4

AIM: A program that creates a web application that implements user


authentication and Authorization.

CODE:

 [Link]
<!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("[Link]
*{
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;

Enrollment No - 2503031057167 55 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

font-family: "Poppins", sans-serif;


font-weight: 300;
transition: .3s;
&:hover{ backgr
ound: #fff; color:
#000; cursor:
pointer;
}
}
</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>

 [Link]
<!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%
);
}

Enrollment No - 2503031057167 56 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

.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;
}
& .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;

Enrollment No - 2503031057167 57 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

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 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>.
Enrollment No - 2503031057167 58 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

</p>
</div>
</body>
</html>

Enrollment No - 2503031057167 59 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 [Link]
<!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>
*{
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;

Enrollment No - 2503031057167 60 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

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;
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;
}

Enrollment No - 2503031057167 61 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

.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 %}
<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>

Enrollment No - 2503031057167 62 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 [Link]
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from [Link] import generate_password_hash, check_password_hash
import secrets

app = Flask( name )


app.secret_key = secrets.token_hex(16)

[Link]['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///[Link]'
db = SQLAlchemy(app)

class User([Link]):
id = [Link]([Link], primary_key=True)
username = [Link]([Link](50), unique=True, nullable=False)
password = [Link]([Link](256), nullable=False)

withapp.app_context():
db.create_all()
@[Link]("/")
def home():
return render_template("[Link]")

@[Link]('/register', methods=['GET', 'POST'])


def register():
if [Link] == 'POST':
username = [Link]['username']
password = [Link]['password']
if [Link].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)
[Link](new_user)
[Link]()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))

return render_template('[Link]')

@[Link]('/login', methods=['GET', 'POST'])


def login():
if [Link] == 'POST':
username = [Link]['username']
password = [Link]['password']

Enrollment No - 2503031057167 63 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

user = [Link].filter_by(username=username).first()

if user and check_password_hash([Link], password):


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

returnrender_template('[Link]')
@[Link]('/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'))

@[Link]('/logout')
def logout():
[Link]('username', None)
flash('You have been logged out.', 'info')
return redirect(url_for('login'))

if name == ' main ':


[Link](debug=True)

Enrollment No - 2503031057167 64 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

 Output:

Enrollment No - 2503031057167 65 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 5

AIM: A program that creates a web application that integrates


with third-party APIs to provide additional functionality.

CODE:

Index_api.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>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<form action="/weather" method="post">
<label for="city">Enter city:</label>
<input type="text" id="city" name="city" required>
<button type="submit">Get Weather</button>
</form>
</body>
</html>

Enrollment No - 2503031057167 66 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

[Link]
<!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>Weather Result</title>
</head>
<body>
<h2>Weather Result</h2>
<p>{{ result }}</p>
<a href="/">Go back</a>
</body>
</html>

 [Link]
from flask import Flask, render_template, request
import requests
app = Flask( name )
def get_weather(api_key, city):
url =
f'[Link]
ey}&units=metric'
response = [Link](url)
data = [Link]()
if response.status_code == 200:

Enrollment No - 2503031057167 67 | P a g e
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

weather_description = data['weather'][0]['description']
temperature = data['main']['temp']
return f'The weather in {city} is {weather_description} with a
temperature of {temperature}°C.'
else:
return 'Failed to fetch weather information.'
@[Link]('/')
def home():
return render_template('index_api.html')
@[Link]('/weather', methods=['POST'])
def weather():
api_key = 'your-openweathermap-api-key' # Replace with your API
key
city = [Link]['city']
result = get_weather(api_key, city)
return render_template([Link]', result=result)
if name == ' main ':
[Link](debug=True)

 Output:

Enrollment No - 2503031057167 68 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

SET-5
PRACTICAL-1

AIM : A program that creates a simple RESTful API that returns a list of
users in JSON format
CODE:
from flask import Flask, jsonify
app = Flask( name )
users = [
{'id': 1, 'name': 'Arshad'},
{'id': 2, 'name': 'Vishnu'},
{'id': 3, 'name': 'Reddy'}
]
@[Link]('/users', methods=['GET'])
def get_users():
return jsonify(users)
if name == ' main ':
[Link](debug=True)


OUTPUT:

Enrollment No - 2503031057167 69 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester


PRACTICAL- 2

AIM: A program that creates a RESTful API that allows users to create,
read, update, and delete resource

CODE:

[Link]
from flask import Flask, jsonify, request
app = Flask( name )
books = [
{'id': 1, 'title': 'Book 1', 'author': 'Author 1'},
{'id': 2, 'title': 'Book 2', 'author': 'Author 2'},
{'id': 3, 'title': 'Book 3', 'author': 'Author 3'}
]
@[Link]('/books', methods=['GET'])
def get_books():
return jsonify(books)
@[Link]('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((b for b in books if b['id'] == book_id), None)
if book:
return jsonify(book)
else:
return jsonify({'error': 'Book not found'}), 404
@[Link]('/books', methods=['POST'])
def create_book():
data = request.get_json()
new_book = {

Enrollment No - 2503031057167 70 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
'id': len(books) + 1,

'title': data['title'],
'author': data['author']
}
[Link](new_book)
return jsonify(new_book), 201
@[Link]('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = next((b for b in books if b['id'] == book_id), None)
if book:
data = request.get_json()
book['title'] = data['title']
book['author'] = data['author']
return jsonify(book)
else:
return jsonify({'error': 'Book not found'}), 404
@[Link]('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
books = [b for b in books if b['id'] != book_id]
return jsonify({'result': True})
if name == ' main ':
[Link](debug=True)

Enrollment No - 2503031057167 71 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

OUTPUT:

Enrollment No - 2503031057167 72 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 3

AIM: A program that creates a RESTful API that authenticates users using a
JSON Web Token

CODE:

[Link]
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required,
create_access_token
app = Flask( name )
# Set up Flask-JWT-Extended
[Link]['JWT_SECRET_KEY'] = 'your-secret-key' # Replace with your
secret key
jwt = JWTManager(app)
# Dummy user data (replace with a proper user database in a real
application)
users = {
'user1': {'password': 'password1'},
'user2': {'password': 'password2'}
}
# Route to generate a JWT token upon login
@[Link]('/login', methods=['POST'])
def login():
data = request.get_json()
username = [Link]('username')
password = [Link]('password')

Enrollment No - 2503031057167 73 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
if username in users and users[username]['password'] == password:
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
else:
return jsonify({'error': 'Invalid username or password'}), 401
# Protected route that requires a valid JWT token for access
@[Link]('/protected', methods=['GET']) @jwt_required()
def protected():
current_user = jwt.get_jwt_identity()
return jsonify(logged_in_as=current_user), 200
if name == ' main ':
[Link](debug=True)

OUTPUT:

Enrollment No - 2503031057167 74 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 4

AIM: A program that creates a RESTful API that paginates the results of a
query to improve performance

CODE:

[Link]
from flask import Flask, jsonify, request
app = Flask( name )
# Dummy data (replace with your actual data source)
items = [f'Item {i}' for i in range(1, 101)]
# Route that supports pagination
@[Link]('/items', methods=['GET'])
def get_items():
page = int([Link]('page', 1))
per_page = int([Link]('per_page', 10))
start_index = (page - 1) * per_page
end_index = start_index + per_page
paginated_items = items[start_index:end_index]
return jsonify({'items': paginated_items, 'page': page,
'per_page': per_page, 'total_items': len(items)})
if name == ' main ':
[Link](debug=True)

Enrollment No - 2503031057167 75 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

OUTPUT:

Enrollment No - 2503031057167 76 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

PRACTICAL- 5

AIM: A program that creates a RESTful API that supports data


validation and error handling.

CODE:

[Link]
from flask_restful import Resource, Api, reqparse
app = Flask( name )
api = Api(app)
# Dummy data (replace with your actual data source)
items = {'1': {'name': 'Item 1', 'price': 10.99},
'2': {'name': 'Item 2', 'price': 19.99}}
# Request parser for input validation
parser = [Link]()
parser.add_argument('name', type=str, required=True, help='Name cannot
be blank')
parser.add_argument('price', type=float, required=True, help='Price
cannot be blank')
class ItemResource(Resource):
def get(self, item_id):
item = [Link](item_id)
if item:
return item
else:
return {'error': 'Item not found'}, 404
def put(self, item_id):
args = parser.parse_args()

Enrollment No - 2503031057167 77 | P a g e
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

items[item_id] = {'name': args['name'], 'price':


args['price']}
return items[item_id], 201
def delete(self, item_id):
if item_id in items:
del items[item_id]
return {'result': True}
else:
return {'error': 'Item not found'}, 404
api.add_resource(ItemResource, '/items/<item_id>')
if name == ' main ':
[Link](debug=True)

 OUTPUT:

Enrollment No - 2503031057167 78 | P a g e

You might also like