Python
Python
BACHELOR OF TECHNOLOGY
IV SEMESTER
Laboratory Manual
Session 2025-26
CERTIFICATE
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
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
fahrenheit2 =int(input("\n"))
celsius2= (fahrenheit-32)*1.8
Output:
PRACTICAL- 2
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:
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:
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
PRACTICAL- 5
OUTPUT:
PRACTICAL-6
OUTPUT:
PRACTICAL- 7
OUTPUT:
OUTPUT:
PRACTICAL- 9
OUTPUT:
PRACTICAL- 10
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
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] = []
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
@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
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">
</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]
@[Link]("/")
def home():
return render_template("[Link]")
[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
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;
& .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>
<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 />
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
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]")
return render_template('[Link]')
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
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'))
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
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
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)
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]
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():
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
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
[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
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
[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
[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]")
return render_template('[Link]')
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()
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'))
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
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
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
OUTPUT:
Enrollment No - 2503031057167 78 | P a g e