Python (1) 1584
Python (1) 1584
BACHELOR OF TECHNOLOGY
IV SEMESTER
Laboratory Manual
Session: 2023-24
Certificate
Sr Date Of Date Of
No. Performance Aim Submission
Signature Marks
SET-1
Set-1
1. A program that converts temperatures from Fahrenheit to Celsius and vice versa.
Code :
f=float(input("Enter Fahrenhit temperature:\n"))
c=(5/9)*(f-32)
print("Celsius:",round(c,2))
Output :
Code :
l=float(input("Enter length:"))
b=float(input("Enter breadth:"))
print("Perimeter of rectangle is:",round(2*(l+b),2))
print("Area of rectangle is:",round(l*b,2))
Output :
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development
Code :
import random
import string
length=int(input("Input the desired length of your password:"))
def generate(length):
a=string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(a) for i in range(length))
return password
password = generate(length)
print(f"Generated password is: {password}")
Output :
Code :
n=int(input())
L1=[]
sum=0
for i in range(n):
k=int(input())
L1.append(k)
sum=sum+k
print(sum/n)
Output:
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development
Code :
year=int(input("Enter year"))
if year%400==0 and year%100==0:
print("This year is leap year")
elif year%4==0 and year%100!=0:
print("This year is leap year")
else :
print("This year is not leap year")
Output :
Code :
n = int(input("Enter number:"))
fact = 1
for i in range(1, n+1):
fact = fact * i
print(f"The factorial of {n} is : ", end="")
print(fact)
Output :
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development
Code :
def pallendrom():
n=int(input())
rem=0
rev=0
temp=n
whilen>0:
rem=n%10
rev=rem+(rev*10)
n=n//10
if rev==temp:
print("pallendrom")
else:
print("not pallendrom")
pallendrom()
Output :
Code :
n=int(input("Enter numder of element"))
L1=[]
for i in range(n):
k=int(input())
L1.append(k)
L1=sorted(L1)
print(f"Ascending order:{L1}")
print(f"Deascending order:{L1[::-1]}")
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development
Output :
Code :
n=int(input("Enter a number:"))
print(f"Table of {n}:")
for i in range(1,11):
print(n,"x",i, "=",i*n)
Output :
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development
10. A program that converts a given number from one base to another.
Code :
n = input("Enter the value to convert: ")
Fb = int(input("Enter the base value from which you want to convert: "))
tb = int(input("Enter the base value to which you want to convert (2, 8, 10, or 16):
"))
Dv = int(str(n), Fb)
if tb == 16:
Cv= format(Dv, 'X')
else:
Cv = format(Dv, 'b' if tb == 2 else '' if tb == 10 else 'o')
print(Cv)
Output :
Enrollmentno : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 -
Programming in Python with Full Stack
Development
INDEX
SET 2
PAGE
INDEX NAME OF DATE OF DATE OF
MARKS SIGN
NO. EXPERIMENT PERFORMANCE SUBMISSION
START-
END
A program that models a
bank account , with classes
1. for the account, the
customer, and the bank
Set-2
1) A Program that models a bank account ,with classes for the account,
the customer and the bank.
CODE :
class Customer:
def init (self, name, address):
self.name = name
self.address = address
class Account:
def init (self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
class Bank:
def init (self, name):
self.name = name
self.accounts = {}
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
# Example usage:
customer1 = Customer("Alice", "123 Main St")
bank = Bank("MyBank")
bank.add_account("220101", customer1)
account = bank.get_account("220101")
account.deposit(1000)
account.withdraw(500)
OUTPUT :
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
CODE:
class SchoolManagement:
def init (self, school_name, address, contact_number,
medium_of_study):
self.school_name = school_name
self.address = address
self.contact_number = contact_number
self.medium_of_study = medium_of_study
class Classroom:
def init (self, class_id, class_name, teacher_id, student_count,
equipment_id):
self.class_id = class_id
self.class_name = class_name
self.teacher_id = teacher_id
self.student_count = student_count
self.equipment_id = equipment_id
class Student:
def init (self, student_id, student_name, class_id, section, bus_id):
self.student_id = student_id
self.student_name = student_name
self.class_id = class_id
self.section = section
self.bus_id = bus_id
class Department:
def init (self, department_id, department_name, incharge_name,
member_list):
self.department_id = department_id
self.department_name = department_name
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
self.incharge_name = incharge_name
self.member_list = member_list
class Teacher:
def init (self, employee_id, employee_name, salary,
department_id):
self.employee_id = employee_id
self.employee_name = employee_name
self.salary = salary
self.department_id = department_id
school = SchoolManagement("ABC School", "123 Main St", "123-456-7890",
"English")
classroom = Classroom(1, "Class 10A", 101, 30, 1)
student = Student(1001, "John Doe", 1, "A", 1)
department = Department(1, "Science", "Dr. Smith", ["Teacher1",
"Teacher2"])
teacher = Teacher(101, "Ms. Johnson", 50000, 1)
print(f"School Name: {school.school_name}")
print(f"Classroom Name: {classroom.class_name}")
print(f"Student Name: {student.student_name}")
print(f"Department Name: {department.department_name}")
print(f"Teacher Name: {teacher.employee_name}")
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
def count(path):
try:
with open(path,'r') as file:
file_content = file.read()
return f"data = {file_content.split()}\nlength of the words:
{len(file_content.split())}"
except FileNotFoundError:
path ="example.txt"
print(count(path))
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
CODE:
import csv
def calculate_average(csv_file, column_name):
try:
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
if column_name not in reader.fieldnames:
print(f"Column '{column_name}' not found in the CSV file.")
return None
total = 0
count = 0
for row in reader:
try:
value = float(row[column_name])
total += value
count += 1
except ValueError:
print(f"Skipping row {reader.line_num}: Invalid value in column
'{column_name}'.")
if count == 0:
print(f"No valid values found in column '{column_name}'.")
return None
average = total / count
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
return average
except FileNotFoundError:
print(f"File '{csv_file}' not found.")
return None
csv_file_path = 'file.csv'
column_to_calculate = 'ENGLISH'
result = calculate_average(csv_file_path, column_to_calculate)
if result is not None:
print(f"The average value in column '{column_to_calculate}' is: {result}")
file.csv:
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
CODE:
import pandas as pd
import openpyxl
output = pd.read_excel("delimited.xlsx")
print(output)
delimited.xlsx:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 -
Programming in Python with Full Stack
Development
INDEX
SET 3
PAGE
INDEX NAME OF DATE OF DATE OF
MARKS SIGN
NO. EXPERIMENT PERFORMANCE SUBMISSION
START-
END
A program that creates a
simple web server and serves
1. a static HTML page.
SET-3
1) A program that creates a simple web server and serves a static HTML
page.
Procedure:
1) Install Flask :
Make sure Flask is installed. Open a terminal and run the following command:
bash
project_folder/
|-- app.py
|-- templates/
| |-- index.html
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
3) HTML FILE:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
app.py
@app.route("/")
def home():
return render_template("index.html")
app.run(debug=True)
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
bash
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Procedure:
1) Setup:
Make sure you have Python installed on your system. Install Flask and Flask-
SQLAlchemy:
bash
pip install Flask Flask-SQLAlchemy
project_folder/
|-- templates/
| |-- index.html
| |-- login.html
| |-- register.html
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
3) HTML FILE:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Static HTML Page</title>
</head>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
display: flex;
justify-content:center;
align-items: center;
flex-direction: column;
background: #ff5a5f;
}
h1 {
font-family: "Poppins", sans-serif;
color: #fff;
margin: 30px 50px;
font-size: 3rem;
}
input {
padding: 10px 20px;
border: 3px solid #fff;
border-radius: 10px;
background: rgb(16, 208, 16);
font-size: 1.5rem;
color: white;
font-family: "Poppins", sans-serif;
font-weight: 300;
transition: .3s;
&:hover{ backgrou
nd:#fff; color:
#000; cursor:
pointer;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and TechnologyB.Tech.
(CSE)4th Sem 303105258 - Programming in Python with
Full Stack
Development
}
}
</style>
<body>
<h1>Hello, this is a static HTML page served by Flask!</h1>
<form action="{{ url_for('register') }}">
<input type="submit" value="Register" />
</form>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Login</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background: rgb(9, 9, 121);
background: linear-
gradient( 30deg,
rgba(9, 9, 121, 1) 0%,
rgba(2, 0, 36, 1) 29%,
rgba(0, 212, 255, 1) 100%
);
}
.container
{ display:
flex;
align-items: center;
justify-content:space-evenly;
flex-direction: column;
width: 600px;
border-radius: 20px;
height: 500px;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and TechnologyB.Tech.
(CSE)4th Sem 303105258 - Programming in Python with
Full Stack
background:#ffffff5a;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
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{ paddin
g: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& .username{ paddin
g: 10px 20px;
border-radius: 20px;
outline: none;
border: none;
}
& input {
margin: 10px 20px;
}
}
}
.error
{ color:red;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
.success
{ color:gree
n;
}
.default
{ color:
black;
}
</style>
</head>
<body>
<div class="container">
<h1>User Login</h1>
{% withmessages = 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 anaccount?
<a href="{{ url_for('register') }}">Register here</a>.
</p>
</div>
</body>
</html>
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Registration</title>
<style>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
font-size:1.2rem;
transition: 0.3s;
transform: translateX(130px);
&:hover {
background:#fff;
color: #000;
cursor: pointer;
}
}
& .password
{ padding: 10px
20px; border-radius:
20px; outline: none;
border: none;
}
& .username
{ padding: 10px
20px; border-radius:
20px; outline: none;
border: none;
}
& input {
margin: 10px 20px;
}
}
}
.error
{ color:red;
}
.success
{ color:gree
n;
}
.default
{ color:
black;
}
</style>
</head>
<body>
<div class="container">
<h1>User Registration</h1>
{% withmessages = get_flashed_messages() %} {% ifmessages %}
<ul>
{% for message in messages %}
<li
class="{% if 'error' in message %}error{% elif 'success' in message %}success{% else %}default{% endif
%}"
>
{{ message }}
</li>
{% endfor %}
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
</ul>
{% endif %} {% endwith %}
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
4) FLASK APPLICATION:
app.py
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import secrets
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(256), nullable=False)
with app.app_context():
db.create_all()
@app.route("/")
def home():
return render_template("index.html")
if User.query.filter_by(username=username).first():
flash('Username already taken. Please choose another.', 'error')
else:
hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
new_user = User(username=username, password=hashed_password)
db.session.add(new_user)
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
db.session.commit()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
user = User.query.filter_by(username=username).first()
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'username' in session:
return f'Welcome to the dashboard, {session["username"]}!'
else:
flash('Please log in to access the dashboard.', 'info')
return redirect(url_for('login'))
@app.route('/logout')
def logout():
session.pop('username', None)
flash('You have been logged out.', 'info')
return redirect(url_for('login'))
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
3) A program that creates a web application that allows users to upload and
download files.
Procedure:
1) Setup:
Make sure you have Python installed on your system.
Install Flask:
bash
pip install Flask
2) Project structure:
project_folder/
|-- templates/
| |-- index.html
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload and Download</title>
</head>
<body>
<h1>File Upload and Download</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="file">Choosea 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>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@app.route('/')
def index():
filenames = os.listdir(app.config['UPLOAD_FOLDER'])
return render_template('index.html', filenames=filenames)
@app.route('/upload', methods=['POST'])
def upload_file():
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
Procedure:
1) Setup:
Ensure you have Python installed on your system.
2) Project structure:
project_folder/
|-- templates/
| |-- index.html
3) HTML FILE :
index.html
<!DOCTYPE html>
<html lang="en">
<head>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Display</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Data Display</h1>
<!-- Render the HTML table -->
{{ table_html | safe }}
</div>
</body>
</html>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
@app.route('/')
defdisplay_data():
# Query data from thedatabase
data = Person.query.all()
returnrender_template('index.html', table_html=table_html)
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
5) A program that creates a web application that accepts user input and
sends it to a server-side script for processing.
Procedure:
1) Setup:
bash
pip install Flask
2) Project Structure:
project_folder/
|-- app.py
|-- templates/
| |-- index.html
3) HTML FILE :
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>User Input</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100%;
background:#a2d2ff;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.container
{ display:flex;
align-items: center;
justify-content:space-evenly;
flex-direction: column;
width: 500px;
height: 600px;
border-radius: 20px;
background:#ffffff5a;
backdrop-filter: blur(20px);
& h1{
font-family: Arial, Helvetica, sans-serif;
color: #3a86ff;
font-size: 2rem;
}
& label{
color: #3a86ff;
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2rem;
padding: 10px;
margin: 10px 20px;
}
& .enter{
padding: 10px 20px;
border: none;
outline: none;
border-radius:20px;
}
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
& .submit{
padding: 10px 20px;
color: #fff;
background:#2a9d8f;
outline: none;
border: none;
border-radius:10px;
transition: .3s;
transform: translateX(150px);
margin: 30px;
&:hover{ color:#00
0; cursor:
pointer;
background:#fff;
}
}
& h2{
font-family: Arial, Helvetica, sans-serif;
color: #3a86ff;
font-size: 2rem;
}
}
</style>
<body>
<div class="container">
<h1>User Input Form</h1>
<form method="post" action="/">
<label for="user_input">Enter something:</label>
<input type="text" class="enter" name="user_input" id="user_input" required />
<br />
<input class="submit" type="submit" value="Submit" />
</form>
{% if result %}
<div>
<h2>Result:</h2>
<p>{{ result }}</p>
</div>
{% endif %}
</div>
</body>
</html>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech.(CSE) 4th Sem 303105257 –
Programming in Python with Full StackDevelopment
OUTPUT:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105257 -
Programming in Python with Full Stack
Development
INDEX
SET-4
PAGE
INDEX NAME OF DATE OF DATE OF
MARKS SIGN
NO. EXPERIMENT PERFORMANCE SUBMISSION
START-
END
A program that creates a
web application that uses a
1. template engine to generate
dynamic HTML pages.
SET4
1) A program that creates a web application that uses a template engine to
generate dynamic HTML pages.
app.py
from flask import Flask, render_template
@app.route('/')
def home():
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
initial-scale=1.0">
<body>
</body>
</html>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment
Output
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment
app.py
from flask import Flask, render_template, request, jsonify
@app.route('/')
def home():
return render_template('index_ajax.html')
@app.route('/update', methods=['POST'])
def update():
data = request.get_json()
message = data['message']
app.run(debug=True)
index_ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
initial-scale=1.0">
<script>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment
{ method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
document.getElementById('output').innerHTML =
responseData.updatedMessage;
}
</script>
</head>
<body>
<button onclick="updateMessage()">Update</button>
<div id="output"></div>
</body>
</html>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment
#!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
try:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
you "
) from exc
execute_from_command_line(sys.argv)
Now, create a directory named mysite with a file named settings.py inside it. Add the
following
content to settings.py:
import os
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.staticfiles',
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors':
[ 'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
WSGI_APPLICATION = 'mysite.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
STATIC_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Create another file in the mysite directory named urls.py with the following content:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
def trigger_error(request):
urlpatterns = [
path('error/', trigger_error),
Now, you can run the Django development server with debugging features. Open a
terminal,
for debugging. Django's built-in debugging features will provide detailed information about
the
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
app.py
from flask import Flask, render_template, request, redirect, url_for, session, flash
import secrets
app.secret_key = secrets.token_hex(16)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
with app.app_context():
db.create_all()
@app.route("/")
def home():
return render_template("index.html")
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if User.query.filter_by(username=username).first():
else:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
db.session.add(new_user)
db.session.commit()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
session['username'] = username
return redirect(url_for('dashboard'))
else:
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'username' in session:
else:
return redirect(url_for('login'))
@app.route('/logout')
def logout():
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
session.pop('username', None)
return redirect(url_for('login'))
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<style>
@import
url("https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap");
* { margin:
0;
padding: 0;
box-sizing: border-box;
body {
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
background: #ff5a5f;
h1 {
color: #fff;
font-size: 3rem;
input {
border-radius: 10px;
font-size: 1.5rem;
color: white;
font-weight: 300;
transition: .3s;
&:hover{ backgr
#000; cursor:
pointer; 6
</style>
<body>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
</form>
</body>
</html>
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<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;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
flex
-direction: column;
background: linear
gradient( 3
0deg,
);
.container
{ display:
flex; align
-items: center;
justify
-content: space
-evenly;
flex
-direction: column;
width: 600px;
border
500px; background:
#ffffff5a; backdrop
-filter: blur(20px);
& h1 {
font
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
-serif;
color: #fff;
margin: 30px 0;
& li
{ list
-style: none;
& form
{ & label
color: white;
font
-serif;
font
-size: 1.4rem;
& .register_button
{ color: #fff;
background: red;
border: none;
outline: none;
border
-radius: 10px;
10
font-size: 1.2rem;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
transition: 0.3s;
transform: translateX(130px);
&:hover {
background: #fff;
color: #000;
cursor: pointer;
& .password
{ padding: 10px
20px; border-radius:
border: none;
& .username
{ padding: 10px
20px; border-radius:
border: none;
& input {
.error
{ color:
red;
.success {
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
color: green;
.default
{ color: black;
</style>
</head>
<body>
<div class="container">
<h1>User Registration</h1>
<ul>
<li
%}"
>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %} {% endwith %}
<br />
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
<br />
</form>
<p>
</p>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Login</title>
<style>
* { margin:
0;
padding: 0;
box-sizing: border-box;
body {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
justify-content: center;
flex-direction: column;
background: linear-
gradient( 30deg,
);
.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
-serif;
color: #fff;
margin: 30px 0;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
& li
{ list
-style: none;
& form
{ & label
color: white;
font
font
-size: 1.4rem;
& .log_button
{ color: #fff;
background: red;
border: none;
outline: none;
border
-radius: 10px;
font
-size: 1.2rem;
transition: 0.3s;
transform: translateX(130px);
&:hover {
background: #fff;
color: #000;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
cursor: pointer;
-radius: 20px;
outline: none;
border: none;
}
& .username{ paddin
-radius: 20px;
outline: none;
border: none;
}
& input {
}}
.error
{ color:
red;
.success
{ color: green;
.default {
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
color: black;
</style>
</head>
<body>
<div class="container">
<h1>User Login</h1>
<ul>
<li
%}"
>
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %} {% endwith %}
<br />
<br />
</form>
<p>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
</p>
</div>
</body>
</html>
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
This example uses the OpenWeatherMap API to fetch current weather information. Before
running the code, you need to sign up for a free API key at https://openweathermap.org/api
Python
url =
f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_k
ey}&units=metric'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
weather_description = data['weather'][0]['description']
temperature = data['main']['temp']
else:
return 'Failed to fetch weather information.'
@app.route('/')
def home():
return render_template('index_api.html')
@app.route('/weather', methods=['POST'])
def weather():
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
<html lang="en">
<head>
<meta charset="UTF-8">
</form>
</body>
</html>
Result.html:
<!DOCTYPE html>
<html lang="en">
<head>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<h2>Weather Result</h2>
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105257 -
Programming in Python with Full Stack
Development
INDEX
SET-5
PAGE
INDEX NAME OF DATE OF DATE OF
MARKS SIGN
NO. EXPERIMENT PERFORMANCE SUBMISSION
START-
END
A program that creates a
simple RESTful API that
1. returns a list of users in JSON
format.
SET5
1) A program that creates a simple RESTful API that returns a list of
users in JSON format.
app.py
A program that creates a simple RESTful API that returns a list of users in JSON
format.
Below is a minimal example of a Flask application that creates a simple RESTful API
to return a
list of users in JSON format.
from flask import Flask, jsonify
app = Flask( name )
users = [
{'id': 1, 'name': 'Arshad'},
{'id': 2, 'name': 'Vishnu'},
{'id': 3, 'name': 'Reddy'}
]
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
if name == ' main ':
app.run(debug=True)
Save this code in a file (e.g., app.py) and run it using: python app.py
This creates a simple Flask application with one route (/users) that returns the list of
users in
JSON format. Visit http://127.0.0.1:5000/users in your web browser or use a tool like
curl or
Postman to make a GET request to see the JSON response:
[
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Doe"}
]
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
2) A program that creates a RESTful API that allows users to create, read,
update, and delete resource.
Below is a minimal example of a Flask application that creates a simple RESTful API
allowing
users to perform CRUD operations on a resource (in this case, a collection of books).
from flask import Flask, jsonify, request
@app.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
@app.route('/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:
'title': data['title'],
'author': data['author']
}
books.append(new_book)
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
return jsonify(book)
else:
return jsonify({'error': 'Book not found'}), 404
@app.route('/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 ':
app.run(debug=True)
This program defines five routes for performing CRUD operations on a collection of books:
● GET /books: Get all books.
● GET /books/<book_id>: Get a specific book by ID.
To test the API, you can use tools like curl or Postman or make requests from a programming
language of your choice. For example, you can use curl to create a new book:
curl -X POST -H "Content-Type: application/json" -d '{"title": "New
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Below is a minimal example of a Flask application that creates a simple RESTful API with
user
authentication using JSON Web Tokens (JWT). This example uses the Flask-JWT-Extended
library, so you need to install it before running the code (pip install Flask
Flask-JWT-Extended).
from flask import Flask, jsonify, request
jwt = JWTManager(app)
# Dummy user data (replace with a proper user database in a real
application)
users = {
'user1': {'password': 'password1'},
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
else:
@jwt_required()
def protected():
current_user = jwt.get_jwt_identity()
return jsonify(logged_in_as=current_user), 200
if name == ' main ':
app.run(debug=True)
To test the API, you can use tools like curl or Postman or make requests from a programming
language of your choice. For example, you can use curl to create a new book:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Below is a minimal example of a Flask application that creates a simple RESTful API
with
pagination to improve performance. This example uses a list of items, and the API
allows clients
to request a specific page of results.
GET /items: Accepts optional query parameters page and per_page to paginate the
results. The
default values are page=1 and per_page=10. The response includes a JSON object
with the
paginated items, current page, items per page, and total number of items.
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
To test the API, you can use tools like curl or Postman or make requests from a
programming
language of your choice. For example, you can use curl to request the second page
with 20
items per page:
curl "http://127.0.0.1:5000/items?page=2&per_page=20
Output:
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Below is a minimal example of a Flask application that creates a simple RESTful API
with data
validation and error handling using the flask_restful extension. You need to install it
before
running the code (pip install Flask Flask-RESTful).
from flask import Flask
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 = reqparse.RequestParser()
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 = items.get(item_id)
if item:
return item
else:
return {'error': 'Item not found'}, 404
def put(self, item_id):
args = parser.parse_args()
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 ':
app.run(debug=True)
This example includes one resource (ItemResource) with three endpoints:
GET /items/<item_id>: Retrieve details for a specific item.
PUT /items/<item_id>: Update details for a specific item.
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment
Output:
Enrollment no : 2203031050611
Division: 4B38_CSE