0% found this document useful (0 votes)
3 views48 pages

Python Lab

The document is a lab manual for a Python programming course in Full Stack Development for B. Tech 4th semester students. It includes a certificate of completion for a student named Mr. Nikhil and outlines various practical exercises covering Python programming basics, object-oriented programming, web application development, advanced web development, and RESTful API development. Each section contains aims, algorithms, programs, and expected outputs for the exercises.

Uploaded by

hashiraboy78
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)
3 views48 pages

Python Lab

The document is a lab manual for a Python programming course in Full Stack Development for B. Tech 4th semester students. It includes a certificate of completion for a student named Mr. Nikhil and outlines various practical exercises covering Python programming basics, object-oriented programming, web application development, advanced web development, and RESTful API development. Each section contains aims, algorithms, programs, and expected outputs for the exercises.

Uploaded by

hashiraboy78
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

Programming in Python with


Full Stack Development
(303105257)
4th SEMESTER
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

LAB MANUAL
CERTIFICATE

This is to certify Mr. Nikhil with Enrollment no.


2403031461270 that Has successfully completed his Laboratory
Experiments in the Programming in Python with Full Stack
Development (303105257) from the Department of Artificial
Intelligence & Machine Learning (AIML) during the academic year
2025-2026.

Date of Submission:

Head of Department : Staff in Charge:


COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

INDEX
Set / TITLE Start End Start End Marks Sign
SR. Page Page Date Date out of 10
No. No. No.
SET – 1 : Python Programming Basics

1 Program to convert temperatures from


Fahrenheit to Celsius and vice versa
2 Program to calculate the area and
perimeter of a rectangle
3 Program to generate a random password
of a specified length
4 Program to calculate the average of a
list of numbers
5 Program to check whether a given year
is a leap year
6 Program to calculate the factorial of a
number
7 Program to check whether a given string
is a palindrome
8 Program to sort a list of numbers in
ascending or descending order
9 Program to generate a multiplication
table for a given number
10 Program to convert a given number
from one base to another
SET – 2 : Object-Oriented Programming & File Handling

1 Program to model a bank account using


classes for account, customer, and bank
2 Program to simulate a school
management system using classes
3 Program to read a text file and count the
number of words
4 Program to read a CSV file and
calculate the average of a specified
column
5 Program to read an Excel file and display
data in tabular format
SET – 3 : Web Application Development
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

1 Program to create a simple web server


and serve a static HTML page
2 Program to create a web application for
user registration and login
3 Program to create a web application for
file upload and download

4 Program to display data from a


database in tabular format using a web
application
5 Program to accept user input and process
it on the server side
SET – 4 : Advanced Web Development

1 Program to generate dynamic HTML


pages using a template engine
2 Program to support AJAX requests and
update web pages without reloading
3 Program to use Django debugging tools
to troubleshoot errors and exceptions
4 Program to implement user
authentication and authorization
5 Program to integrate third-party APIs
into a web application
SET – 5 : RESTful API Development

1 Program to create a RESTful API that


returns user data in JSON format
2 Program to implement CRUD
operations using RESTful APIs
3 Program to authenticate RESTful APIs
using JSON Web Token (JWT)
4 Program to implement pagination in
RESTful APIs
5 Program to implement data validation
and error handling in RESTful APIs
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

SET – 1 : Python Programming Basics

Practical 1 :
Aim
To write a Python program that converts temperature from Fahrenheit to Celsius and vice
versa.
Algorithm
1. Input temperature value
2. Ask user for conversion choice
3. Apply appropriate formula
4. Display the converted temperature
Program
temp = float(input("Enter temperature: "))
choice = input("Convert to (C/F): ")

if [Link]() == 'C':
c = (temp - 32) * 5 / 9
print("Temperature in Celsius:", c)
elif [Link]() == 'F':
f = (temp * 9 / 5) + 32
print("Temperature in Fahrenheit:",
f) else:
print("Invalid choice")
Output
Enter temperature: 98
Convert to (C/F): C
Temperature in Celsius: 36.66

Practical 2
Aim
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

To calculate the area and perimeter of a rectangle.


Algorithm
1. Input length and breadth
2. Calculate area = l × b
3. Calculate perimeter = 2(l + b)
4. Display results
Program
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))

area = l * b
perimeter = 2 * (l + b)

print("Area:", area)
print("Perimeter:", perimeter)
Output
Area: 50
Perimeter: 30

Practical 3
Aim
To generate a random password of specified length.
Algorithm
1. Input password length
2. Use letters, digits, and symbols
3. Generate random characters
4. Display password
Program
import random
import string
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

length = int(input("Enter password length: "))


chars = string.ascii_letters + [Link] + [Link]
password = ''.join([Link](chars) for i in range(length))

print("Generated Password:", password)


Output
Generated Password: A@9x#2B!

Practical 4
Aim
To calculate the average of a list of numbers.
Algorithm
1. Input numbers as a list
2. Find sum of list
3. Divide by number of elements
4. Display average
Program
nums = list(map(int, input("Enter numbers: ").split()))
avg = sum(nums) / len(nums)
print("Average:", avg)
Output
Enter numbers: 10 20 30
Average: 20.0

Practical 5
Aim
To check whether a given year is a leap year.
Algorithm
1. Input year
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

2. Apply leap year conditions


3. Display result
Program
year = int(input("Enter year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):


print("Leap Year")
else:
print("Not a Leap Year")
Output
Enter year: 2024
Leap Year

Practical 6
Aim
To calculate factorial of a given number.
Algorithm
1. Input number
2. Multiply numbers from 1 to n
3. Display factorial
Program
n = int(input("Enter number: "))
fact = 1

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


fact *= i

print("Factorial:", fact)
Output
Enter number: 5
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

Factorial: 120

Practical 7
Aim
To check whether a string is a palindrome.
Algorithm
1. Input string
2. Reverse the string
3. Compare original and reversed
4. Display result
Program
s = input("Enter string: ")

if s == s[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
Output
Enter string: madam
Palindrome

Practical 8
Aim
To sort a list of numbers in ascending or descending order.
Algorithm
1. Input list
2. Ask sorting order
3. Sort accordingly
4. Display result
Program
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

nums = list(map(int, input("Enter numbers: ").split()))


order = input("asc or desc: ")

if order == "asc":
[Link]()
else:
[Link](reverse=True)

print("Sorted List:", nums)


Output
Sorted List: [10, 20, 30]

Practical 9
Aim
To generate a multiplication table for a given number.
Algorithm
1. Input number
2. Loop from 1 to 10
3. Print multiplication
Program
n = int(input("Enter number: "))

for i in range(1, 11):


print(n, "x", i, "=", n * i)
Output
5x1=55
x 2 = 10
...

Practical 10
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

Aim
To convert a given number from one base to another.
Algorithm
1. Input number and base
2. Convert using built-in functions
3. Display result
Program
num = int(input("Enter number: "))
print("Binary:", bin(num))
print("Octal:", oct(num))
print("Hexadecimal:", hex(num))
Output
Binary: 0b1010
Octal: 0o12
Hexadecimal: 0xa
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

SET – 2 : Object-Oriented Programming & File Handling

Practical 1
Aim
To model a bank account system using classes for Account, Customer, and Bank.
Algorithm
1. Create Customer class
2. Create Account class with deposit & withdraw
3. Create Bank class to manage accounts
4. Perform operations
Program
class Customer:
def init (self, name):
[Link] = name

class Account:
def init (self, acc_no, balance):
self.acc_no = acc_no
[Link] = balance

def deposit(self, amt):


[Link] += amt

def withdraw(self, amt):


if amt <= [Link]:
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

[Link] -= amt
else:
print("Insufficient Balance")

class Bank:
def init (self):
[Link] = []
def
add_account(self,acco
unt):
[Link]
account)

cust = Customer("Aryan")
acc = Account(101, 5000)
[Link](2000)
[Link](1000)
print("Final Balance:", [Link])
Output
Final Balance: 6000

Practical 2
Aim
To simulate a school management system using classes.
Algorithm
1. Create Student, Teacher, Course classes
2. Assign course to students
3. Display details
Program
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

class Student: def


init (self, name):
[Link] = name

class Teacher:
def init (self, name):
[Link] = name

class Course:
def init (self, cname):
[Link] = cname

s = Student("Ravi")
t = Teacher("[Link]")
c = Course("Python")
print("Student:", [Link])
print("Teacher:", [Link])
print("Course:", [Link])
Output
Student: Ravi
Teacher: Mr. Sharma
Course: Python

Practical 3
Aim
To read a text file and count the number of words in it.
Algorithm
1. Open text file
2. Read content
3. Split words
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

4. Count words
Program
file = open("[Link]", "r")
text = [Link]()
words = [Link]()
print("Word Count:",len(words))
[Link]()
Output
Word Count: 45

Practical 4
Aim
To read a CSV file and calculate the average of values in a specified column.
Algorithm
1. Open CSV file
2. Read values from column
3. Calculate average
4. Display result
Program
import csv

with open("[Link]", "r") as file:


reader = [Link](file)
next(reader)
total = 0
count = 0
for row in reader:
total += int(row[1])
count += 1
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

print("Average:", total / count)


Output
Average: 72.5

Practical 5
Aim
To read an Excel file and display data in tabular format.
Algorithm
1. Load Excel file
2. Read rows
3. Print data
Program
import openpyxl

wb = openpyxl.load_workbook("[Link]")
sheet = [Link]

for row in sheet.iter_rows(values_only=True):


print(row)
Output
('Name', 'Marks')
('Amit', 80)
('Neha', 90)
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

SET – 3 : Web Application Development (Flask)

Practical 1
Aim
To create a simple web server and serve a static HTML page.
Algorithm
1. Install Flask
2. Create Flask app
3. Define route
4. Serve HTML page
Program
from flask import Flask

app = Flask( name )

@[Link]("/")
def home():
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

return "<h1>Welcome to My Web Server</h1>"

if name == " main ":


[Link](debug=True)
Output
Web page displays: Welcome to My Web Server

Practical 2
Aim
To create a web application that allows users to register and login.
Algorithm
1. Create registration form
2. Store username & password
3. Validate login credentials
4. Display result
Program
from flask import Flask, request

app = Flask( name )


users = {}

@[Link]("/register", methods=["POST"])
def register():
users[[Link]['username']] = [Link]['password']
return "Registered Successfully"

@[Link]("/login", methods=["POST"])
def login():
if [Link]([Link]['username']) == [Link]['password']:
return "Login Successful"
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

return "Invalid Credentials"

if name == " main ":


[Link](debug=True)
Output
Login Successful

Practical 3
Aim
To create a web application that allows users to upload and download files.
Algorithm
1. Accept file from user
2. Save file on server
3. Allow file download

Program
from flask import Flask, request

app = Flask( name )

@[Link]("/upload", methods=["POST"])

def upload():

file = [Link]['file']
[Link]([Link])
return "File Uploaded Successfully"

if name == " main ":


[Link](debug=True)
Output
File Uploaded Successfully
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

Practical 4
Aim
To display data from a database in tabular format using a web application.
Algorithm
1. Connect to database
2. Fetch records
3. Display in HTML table
Program
from flask import Flask import
sqlite3

app = Flask( name )

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


con = [Link]("[Link]")
cur = [Link]()
[Link]("SELECT * FROM student")
rows = [Link]()
return str(rows)

if name == " main ":


[Link](debug=True)
Output
[(1, 'Amit', 85), (2, 'Neha', 90)]

Practical 5 Aim
To create a web application that accepts user input and processes it on the server side.
Algorithm
1. Accept input from user
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270

2. Process input
3. Display result
Program
from flask import Flask, request

app = Flask( name )

@[Link]("/square", methods=["POST"])
def square():
num = int([Link]['number'])
return f"Square is {num*num}"

if name == " main ":


[Link](debug=True)
Output
Square is 25
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

SET-4

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

 [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Page</title>
</head>
<body>
<div style="background-color:cadetblue">
<h1 style="color: black;">This is HTML page.</h1>
</div>
</body>
</html>

 [Link]
from [Link] import render

# Create your views


here. def
index(request):
return render(request, '[Link]')

. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

 [Link]
from [Link] import path
from . import views

urlpatterns = [
path('', [Link], name='index'),
]

OUTPUT:

. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

PRACTICAL- 2

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


requests and updates the page without reloading

CODE:

[Link]

<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo</title>
</head>
<body>
<h2>AJAX Example</h2>
<button onclick="loadData()">Click Me</button>
<p id="result"></p>
<script>
function loadData() {
fetch('/get-data/')
.then(response => [Link]())
.then(data => {
[Link]("result").innerHTML = [Link];
});
}
</script>
</body>
</html>

 [Link]
from [Link] import render
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
from [Link] import JsonResponse

# Create your views here.


def home(request):
return render(request, "[Link]")

def get_data(request):
return JsonResponse({"message": "Hello! Page updated without reload..!"})

[Link]
from [Link] import path
from . import views

urlpatterns = [
path('', [Link], name='home'),
path('get-data/', views.get_data),
]

OUTPUT:

. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

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]

from [Link] import render


from [Link] import HttpResponse

# Create your views here.


def home(request):
return HttpResponse("Working fine!")

def trigger_error(request):
x = 10 / 0 # Intentional error (ZeroDivisionError)
return HttpResponse("This will never run")

[Link]

from [Link] import path


from . import views

urlpatterns = [
path('', [Link]),
path('error/', views.trigger_error),
]
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

OUTPUT:

. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

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 name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="navbar">
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/join/">Join Us</a>
<a href="/logout/">Logout</a>
</div>
<div class="header">
<h1>Welcome</h1>
</div>
<br>
<div class="content">
<h2 class="contentText">About</h2>
<p class="contentText">This website is created using basic HTML tags and
CSS.</p>
<a href="/about/"><button class="btn">Go to about page</button></a>

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

. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270

 [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="content">
<h1>Signup</h1><br><br>
{% if messages %}
<div>
{% for msg in messages %}
{{ msg }}
{% endfo %}
</div>
{% endif %}
<form action="/signup/" method="POST" class="contentText">
{% csrf_token %}
<label for="email">Email: </label>
<input type="email" name="email"><br><br>
<label for="password">Password: </label>
<input type="password" name="password"><br><br>
<label for="password">Confirm Password: </label>
<input type="password" name="confirmPassword"><br><br>
<button type="submit" class="btn">Submit</button>

</form>
<p class="contentText">Already have an account?</p>
<a href="login" class="contentText">Login here</a><br><br>
</div>
</body>
</html>

[Link]

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="content">
<h1>Login</h1><br><br>
{% if messages %}
<div>
{% for msg in messages %}
{{ msg }}
{% endfor %}
</div>
{% endif %}
<form action="/login/" method="POST"
class="contentText">
{% csrf_token %}
<label for="email">Email: </label>
<input type="email" name="email"><br><br>
<label for="password">Password: </label>
<input type="password" name="password"><br><br>
<button type="submit" class="btn">Submit</button>
</form>
<p class="contentText">Don't have an account ?</p>
<a href="signup" class="contentText">Signup
here</a><br><br>
</div>
</body>
</html>

[Link]

.navbar{
background-color: #170503;
font-size: 23px;
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

text-align: center;
padding: 10px;
}
.navbar a{
color: white;
margin: 0 15px;
font-weight: bold;
text-decoration: none;
}

.navbar a:hover{
text-decoration: underline;
}
.header {
background-color: #9c7b5f;
text-align: center;
padding: 20px;
color: white;
}
.content{
background-color: #9c7b5f;
padding: 20px;
margin: 20px;
color: white;
}

.contentText{
color: white;
}

.btn{
background-color: #9c7b5f;
padding: 10px;
cursor: pointer;
color: white;
border: none;
font-size: 15px;
}

.btn:hover{
background-color: #170503;
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

.input {
padding: 8px;
margin: 5px;
width: 250px;
}

 [Link]
from [Link] import render, redirect
from [Link] import HttpResponse
from [Link] import connection
from .models import *
from [Link] import authenticate, login, logout
from [Link] import login_required
from [Link] import messages
from [Link] import User

# Create your views here.


# def index(request):
# return HttpResponse("Hii..!")

@login_required(login_url='/login/')
def index(request):
return render(request, '[Link]')

def signup_page(request):
if [Link] == 'POST':
username = [Link]('email')
password = [Link]('password')
confirmPassword = [Link]('confirmPassword')

if password != confirmPassword:
[Link](request, "Passwords do not match.")

user = [Link](username=username)
if [Link]():
[Link](request, "User already exists.")
return redirect('/login/')
else:
user = [Link].create_user(username=username)
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

user.set_password(password)
[Link]()
return redirect('/login/')
return render(request, '[Link]')

def login_page(request):
if [Link] == "POST":
username = [Link]("email")
password = [Link]("password")

if not [Link](username=username).exists():
[Link](request, "Invalid email.")
return redirect('/login/')

user = authenticate(username=username,
password=password)

if user is None:
[Link](request, "Invalid credentials.")
return redirect('/login/')
else:
login(request, user)
return redirect('/index/')
return render(request, '[Link]')

@login_required(login_url='/login/')
def logout_page(request):
logout(request)
return redirect('/login/')

[Link]

from [Link] import path


from . import views

urlpatterns = [
path("", views.signup_page, name="signup"),
path("signup/", views.signup_page, name="signup"),
path("login/", views.login_page, name="login"),
path("logout/", views.logout_page, name="logout"),
path("index/", [Link], name="index"),
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester

OUTPUT:

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

. .
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:

 [Link]
from flask import Flask, jsonify
import requests

app = Flask( name )

@[Link]('/users')
def get_users():
response = [Link]("[Link]
data = [Link]()
return jsonify(data)

if name == " main ":


[Link](debug=True)

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

OUTPUT:

. .
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, request, jsonify

app = Flask( name )

data = [
{"name": "abc", "enrollment_number": 12345, "age": 19},
{"name": "pqr", "enrollment_number": 67890, "age": 20}
]

@[Link]('/user', methods=['GET'])
def get_user():
return jsonify(data)

if name == ' main ':


[Link](debug=True)

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


OUTPUT:

.
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, request, jsonify

app = Flask( name )

data = [
{"name": "abc", "enrollment_number": 12345, "age": 19},
{"name": "pqr", "enrollment_number": 67890, "age": 20}
]

# GET
@[Link]('/user', methods=['GET'])
def get_user():
return jsonify(data)

# POST
@[Link]('/user', methods=['POST'])
def add_user():
new_user = [Link]
[Link](new_user)
return jsonify({"message": "User added", "data": data})

# PUT
@[Link]('/user/<int:enrollment_number>', methods=['PUT'])
def update_user(enrollment_number):
for user in data:
if user['enrollment_number'] == enrollment_number:
user['name'] = [Link]('name', user['name'])
user['age'] = [Link]('age', user['age'])
return jsonify({"message": "User updated", "data": user})

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

return jsonify({"message": "User not found"})

# DELETE
@[Link]('/user/<int:enrollment_number>', methods=['DELETE'])
def delete_user(enrollment_number):
for i in range(len(data)):
if data[i]["enrollment_number"] == enrollment_number:
deleted_user = [Link](i)
return jsonify({
"message": "Student deleted successfully",
"deleted_student": deleted_user
})

return jsonify({"message": "Student not found"})

if name == ' main ':


[Link](debug=True)

OUTPUT:

. .
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, request, jsonify


import jwt

app = Flask( name )

SECRET_KEY = "mysecret"

# Login route to generate token


@[Link]('/login', methods=['POST'])
def login():
username = [Link]("username")
password = [Link]("password")

if username == "admin" and password == "123":


token = [Link]({"user": username}, SECRET_KEY, algorithm="HS256")
return jsonify({"token": token})
else:
return jsonify({"message": "Invalid credentials"}), 401

# Protected route
@[Link]('/profile')
def profile():
token = [Link]("Authorization")

try:
data = [Link](token, SECRET_KEY, algorithms=["HS256"])
return jsonify({"message": "Welcome " + data["user"]})
except:
return jsonify({"message": "Invalid or missing token"}), 403
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester

if name == " main ":


[Link](debug=True)

OUTPUT:

. .
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 )

# Sample data
users = [
{"id": 1, "name": "A"},
{"id": 2, "name": "B"},
{"id": 3, "name": "C"},
{"id": 4, "name": "D"},
{"id": 5, "name": "E"},
{"id": 6, "name": "F"},
{"id": 7, "name": "G"},
{"id": 8, "name": "H"},
{"id": 9, "name": "I"},
{"id": 10, "name": "J"}
]

@[Link]('/users', methods=['GET'])
def get_users():
page = int([Link]('page', 1))
per_page = int([Link]('per_page', 3))

start = (page - 1) * per_page


end = start + per_page

paginated_users = users[start:end]

return jsonify(paginated_users)

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

if name == ' main ':


[Link](debug=True)

OUTPUT:

. .
PRACTICAL- 5

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


validation and error handling.

CODE:

[Link]

from flask import Flask, request, jsonify

app = Flask( name )

users = []

@[Link]('/users', methods=['POST'])
def add_user():
try:
data = request.get_json()

# Validation
if not [Link]("name"):
return jsonify({"error": "Name is required"}), 400

if not [Link]("age"):
return jsonify({"error": "Age is required"}), 400

if not isinstance(data["age"], int):


return jsonify({"error": "Age must be a number"}), 400

user = {
"name": data["name"],
"age": data["age"]
}

[Link](user)

. .
return jsonify({
"message": "User added successfully",

"user": user
}), 201

except Exception as e:
return jsonify({"error": str(e)}), 500

@[Link]('/users', methods=['GET'])
def get_users():
return jsonify(users)

if name == " main ":


[Link](debug=True)

OUTPUT:

. .

. .

You might also like