0% found this document useful (0 votes)
6 views85 pages

Python (1) 1584

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)
6 views85 pages

Python (1) 1584

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY

PYTHON FULL STACK DEVELOPMENT


(303105257)

IV SEMESTER

Computer Science & Engineering Department

Laboratory Manual
Session: 2023-24
Certificate

This is to certify that Ms/Mr with

enrollment no. has successfully

completed his/her laboratory programs in the subject with Code

from the department of

during the academic year .

Date of submission Faculty in charge

Head of the Department


INDEX

Sr Date Of Date Of
No. Performance Aim Submission
Signature Marks

SET-1

1 28/11/23 Temperature conversion

2 28/11/23 Area and Perimeter of rectangle

3 5/12/23 Random Password generation

4 5/12/23 Average of a List

5 12/12/23 Leap Year validation

6 12/12/23 Factorial of a number

7 19/12/23 Check string if Palindrome

8 19/12/23 Sorting a List

9 26/12/23 Multiplication table of a number

10 26/12/23 Base Conversion of a number


Parul Institute of Engineering and Technology
B.Tech. (CSE) 4thSem
303105258 - Programing in Python with Full Stack
Development

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 :

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

 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

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

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

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

 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

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

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

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

 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

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

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

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

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

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

 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

A program that stimulates a


2. school management system,
with classes for the student ,
the teachers , and the courses

A program that reads a text


3. file and counts the number
of words in it.

A program that reads a CSV


4. file and calculates the
average of the values in a
specified column.

A program that reads an


5. Excel file and prints the data
in a tabular format.
Parul Institute of Engineering and Technology
B.Tech. (CSE) 4th Sem 303105258 - Programming
in Python with Full Stack
Development

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

def deposit(self, amount):


if amount > 0:
self.balance += amount
print(f"Deposit of ${amount} successful. New balance: ${self.balance}")
else:
print("Invalid amount for deposit.")

def withdraw(self, amount):


if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrawal of ${amount} successful. New balance: ${self.balance}")
else:
print("Insufficient funds or invalid amount for withdrawal.")

class Bank:
def init (self, name):
self.name = name
self.accounts = {}

def add_account(self, account_number, customer):


if account_number not in 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

self.accounts[account_number] = {'customer': customer, 'account':


Account(account_number)}
print(f"Account {account_number} created for customer {customer.name}.")
else:
print(f"Account {account_number} already exists.")

def get_account(self, account_number):


if account_number in self.accounts:
return self.accounts[account_number]['account']
else:
print("Account not found.")
return None

# 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

2) A program that stimulates a school management system, with classes


for the student , the teachers , and the courses.

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

3) 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 = file.read()
return f"data = {file_content.split()}\nlength of the words:
{len(file_content.split())}"
except FileNotFoundError:

return "Please Provide valid file path."

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

4) 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 = 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

5) 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("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.

A program that creates a


2. web application that allows
users to register and login.

A program that creates a


3. web application that allows
users to upload and
download files.

A program that creates a


4. web application that
displays data from a
database in a tabular
format.

A program that creates a


5. web application that accepts
user input and sends it to a
server-side script for
processing.
Parul Institute of Engineering and TechnologyB.Tech.
(CSE)4th Sem 303105258 - Programming in Python with
Full Stack
Development

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

pip install Flask

2) Create Project Structure :


Create a folder for your project and inside it, create two files - app.py for your Flask application and
a folder named templates to store the HTML file.

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

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Static HTML Page</title>

</head>

<body>

<h1>Hello World!</h1>

</body>

</html>

4) Write the Flask App :


Open app.py in a text editor and write the Flask application code:

app.py

from flask import Flask, render_template

app = Flask( name )

@app.route("/")

def home():

return render_template("index.html")

if name == " main ":

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

5) Run the Flask App :

bash

flask --app app run

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 web application that allows users to


register and login.

Procedure:
1) Setup:

Make sure you have Python installed on your system. Install Flask and Flask-
SQLAlchemy:

bash
pip install Flask Flask-SQLAlchemy

2) Create Project Structure :


Create a folder for your project and inside it, create two files - app.py for your Flask application and
a folder named templates to store the HTML file.

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>

Enro llment no : 2203031050611


Division: 4B38_CSE
Parul Institute of Engineering and TechnologyB.Tech.
(CSE)4th Sem 303105257 - Programming in Python with
Full Stack
Development
*{
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;
}
& 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;
Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and TechnologyB.Tech.
(CSE)4th Sem 303105257 - Programming in Python with
Full Stack
Development
padding: 5px 10px;
border-radius:10px;

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

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

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

app = Flask( name )


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

@app.route('/register', methods=['GET', 'POST'])


def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

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

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


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

user = User.query.filter_by(username=username).first()

if user and check_password_hash(user.password, password):


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

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

if name == ' main ':


app.run(debug=True)

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

3) Write html files:

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>

4) Run the Application:


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

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():

if 'file' not in request.files:


return "No file part"
file = request.files['file']
if file.filename == '':
return "No selected file"
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return redirect(url_for('index'))
@app.route('/download/<filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if name == ' main ':
app.run(debug=True)

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

4) A program that creates a web application that displays data from a


database in a tabular format.

Procedure:
1) Setup:
 Ensure you have Python installed on your system.

 Install Flask and SQLAlchemy:


bash
pip install Flask Flask-SQLAlchemy pandas

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>

4) Run the Application:


app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import pandas as pd

app = Flask( name )


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Createa SQLAlchemy instance


db = SQLAlchemy(app)

# Define a model for the data


class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
age = db.Column(db.Integer, nullable=False)

# Sample data for demonstration


sample_data = [{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 22}]

# Populate the database with sample data


with app.app_context():
db.create_all()
for entry in sample_data:
person = Person(name=entry['name'], age=entry['age'])
db.session.add(person)
db.session.commit()

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

# Convert the data to a Pandas DataFrame


df = pd.DataFrame([(person.name, person.age) for person in data], columns=['name', 'age'])

# Convert the DataFrame to HTML for rendering in the template


table_html = df.to_html(classes='table table-striped', index=False)

returnrender_template('index.html', table_html=table_html)

if name == ' main ':


app.run(debug=True)

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:

 Ensure you have Python installed on your system.


 Install Flask:

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

4) Run the Application :


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

if name == ' main ':


app.run(debug=True)

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.

A program that creates a


2. web application that supports
AJAX requests and updates
the page without reloading.

A program that creates a


3. web application that uses
Django's built-in debugging
features to troubleshoot
errors and exceptions.
A program that creates a
4. web application that
implements user
authentication and
Authorization.

A program that creates a


5. web application that
integrates with third- party
APIs to provide additional
functionality.
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment

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 = Flask( name )

@app.route('/')

def home():

return render_template('index.html', message='Hello, World!')

if name == ' main ':

app.run(debug=True)

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>Flask Template Example</title>


</head>

<body>

<h1>{{ message }}</h1>

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

2) A program that creates a web application that supports AJAX requests


and updates the page without reloading.

app.py
from flask import Flask, render_template, request, jsonify

app = Flask( name )

@app.route('/')

def home():

return render_template('index_ajax.html')

@app.route('/update', methods=['POST'])

def update():

data = request.get_json()

message = data['message']

return jsonify({'updatedMessage': message})

if name == ' main ':

app.run(debug=True)

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 = document.getElementById('message');

const message = messageInput.value;

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105257 –
Programming in Python with Full StackDevelopment

const response = await fetch('/update',

{ method: 'POST',

headers: {

'Content-Type': 'application/json',

},

body: JSON.stringify({ 'message': message }),

});

const responseData = await response.json();

document.getElementById('output').innerHTML =

responseData.updatedMessage;

}
</script>

</head>

<body>

<h1>Flask AJAX Example</h1>

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

<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

3) A program that creates a web application that uses Django's built-in


debugging features to troubleshoot errors and exceptions.

Create a file named manage.py with the following content:

#!/usr/bin/env python

import os

import sys

if name == " main ":

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

try:

from django.core.management 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(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

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( file )))

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',

'DIRS': [os.path.join(BASE_DIR, 'templates')],

'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',

'NAME': os.path.join(BASE_DIR, 'db.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

from django.urls import path

from django.http import HttpResponseServerError

def trigger_error(request):

return HttpResponseServerError("Intentional Error for Debugging")

urlpatterns = [

path('error/', trigger_error),

Now, you can run the Django development server with debugging features. Open a
terminal,

navigate to the directory containing manage.py, and execute:

python manage.py runserver

Visit http://127.0.0.1:8000/error/ in your web browser to intentionally trigger an error

for debugging. Django's built-in debugging features will provide detailed information about
the

error, helping you troubleshoot and fix issues.

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

4) A program that creates a web application that implements user


authentication and Authorization.

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

app = Flask( name )

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)

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

@app.route('/register', methods=['GET', 'POST'])

def register():

if request.method == 'POST':
username = request.form['username']

password = request.form['password']

if User.query.filter_by(username=username).first():

flash('Username already taken. Please choose another.', 'error')

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

hashed_password = generate_password_hash(password, method='pbkdf2:sha256')

new_user = User(username=username, password=hashed_password)

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

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

def login():

if request.method == 'POST':

username = request.form['username']

password = request.form['password']

user = User.query.filter_by(username=username).first()

if user and check_password_hash(user.password, password):

session['username'] = username

flash('Login successful!', 'success')

return redirect(url_for('dashboard'))

else:

flash('Invalid username or password. Please try again.', 'error')

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():

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)

flash('You have been logged out.', 'info')

return redirect(url_for('login'))

if name == ' main ':

app.run(debug=True)

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;

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 {

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{ backgr

ound: #fff; color:

#000; cursor:

pointer; 6

</style>

<body>

<h1>Hello, this is a static HTML page served by Flask!</h1>

<form action="{{ url_for('register') }}">

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

<input type="submit" value="Register" />

</form>

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

* { 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: rgb(9, 9, 121);

background: linear

gradient( 3

0deg,

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

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

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

& .register_button

{ color: #fff;

background: red;

border: none;

outline: none;

padding: 5px 10px;

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:

20px; outline: none;

border: none;

& .username

{ padding: 10px

20px; border-radius:

20px; outline: none;

border: none;

& input {

margin: 10px 20px;

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

{% 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 />

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

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

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;

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

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

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

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;

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

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

{% 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>

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

Don't have an account?

<a href="{{ url_for('register') }}">Register here</a>.

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

5) A program that creates a web application that integrates with third-


party APIs to provide additional functionality.

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

from flask import Flask, render_template, request


import requests
app = Flask( name )
def get_weather(api_key, city):

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']

return f'The weather in {city} is {weather_description} with a


temperature of {temperature}°C.'

else:
return 'Failed to fetch weather information.'
@app.route('/')
def home():

return render_template('index_api.html')
@app.route('/weather', methods=['POST'])

def weather():

api_key = 'your-openweathermap-api-key' # Replace with your API


key
city = request.form['city']

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

result = get_weather(api_key, city)

return render_template('result.html', result=result)


if name == ' main ':
app.run(debug=True)
Create a folder named templates in the same directory as your Python file. Inside the
templates
folder, create two HTML files named index_api.html and result.html with the following
content:
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>
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">

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

Replace 'your-openweathermap-api-key' with your actual OpenWeatherMap API key. To run


the
application, execute: python your_filename.py
Visit http://127.0.0.1:5000/ in your web browser, enter a city, and click "Get Weather" to see
the

current weather information fetched from the OpenWeatherMap API

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.

A program that creates a


2. RESTful API that allows users
to create, read, update, and
delete resource.

A program that creates a


3. RESTful API that
authenticates users using a
JSON Web Token.

A program that creates a


4. RESTful API that paginates
the results of a query to
improve performance.

A program that creates a


5. RESTful API that supports
data validation and error
handling.
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

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 = 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'}


]

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

return jsonify({'error': 'Book not found'}), 404


@app.route('/books', methods=['POST'])
def create_book():
data = request.get_json()
new_book = {
'id': len(books) + 1,

'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(new_book), 201


@app.route('/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
@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.

● POST /books: Create a new book.


● PUT /books/<book_id>: Update a specific book by ID.
● DELETE /books/<book_id>: Delete 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

Book", "author": "New Author"}' http://127.0.0.1:5000/books


And then retrieve all books:
curl http://127.0.0.1:5000/books

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) A program that creates a RESTful API that authenticates users using a


JSON Web Token.

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

from flask_jwt_extended import JWTManager, jwt_required,


create_access_token
app = Flask( name )
# Set up Flask-JWT-Extended

app.config['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


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

def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')

if username in users and users[username]['password'] == password:


access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)

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:

return jsonify({'error': 'Invalid username or password'}), 401

# Protected route that requires a valid JWT token for access


@app.route('/protected', methods=['GET'])

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

Replace 'your-secret-key' with a secure secret key of your choice.


This program includes two routes:
● POST /login: Accepts a JSON payload with a username and password. If the credentials
are valid, it returns a JWT token.
● GET /protected: A protected route that requires a valid JWT token for access. It uses the
@jwt_required() decorator to enforce authentication.

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 '{"username":


"user1", "password": "password1"}' http://127.0.0.1:5000/login
And then use the obtained token to access the protected route:
curl -X GET -H "Authorization: Bearer <token>"
http://127.0.0.1:5000/protected

Enrollment no : 2203031050611
Division: 4B38_CSE
Parul Institute of Engineering and Technology B.Tech.
(CSE)4th Sem 303105258 –
Programming in Python with Full StackDevelopment

4) A program that creates a RESTful API that paginates the results of a


query to improve performance.

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.

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
@app.route('/items', methods=['GET'])
def get_items():

page = int(request.args.get('page', 1))


per_page = int(request.args.get('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 ':
app.run(debug=True)
his example includes one route:

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

5) A program that creates a RESTful API that supports data validation


and error handling.

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

DELETE /items/<item_id>: Delete a specific item. The reqparse.RequestParser is


used for input
validation, ensuring that the required fields (name and price) are present and have the
correct
data types.
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 update an item:
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated
Item", "price": 15.99}' http://127.0.0.1:5000/items/1
This example is a basic starting point, and you can expand it based on your specific
requirements, including more advanced data validation and error handling

Output:

Enrollment no : 2203031050611
Division: 4B38_CSE

You might also like