Top Python Web Development Projects – With Source Code


Python is widely recognized for its effectiveness in backend development, a crucial aspect of web development responsible for managing the server-side operations of websites and applications. The language’s popularity in this domain stems from its ability to deliver optimal performance and rapid response times to users.

In the realm of web development, Python has demonstrated significant success, offering compatibility and favorable outcomes for both businesses and end-users alike. Python’s versatility in this arena encompasses a spectrum of tasks, including data exchange with servers, processing of data, communication with databases, security management, URL routing, and more.

Python boasts an array of convenient libraries that streamline web development tasks. Two prominent examples are Flask and Django, both of which are renowned for their scalability, security features, and user-friendly nature. These libraries empower developers to create robust and feature-rich web applications efficiently.

One of Python’s standout features is its dynamic typing system, which enables scripts to execute seamlessly at runtime without requiring translation or compilation. This characteristic results in reduced code complexity compared to other languages with more rigid typing systems. Additionally, Python’s built-in debugging capabilities simplify the debugging process, enhancing the manageability of Python-based web development projects.

Engaging in Python projects offers developers an invaluable opportunity to explore the language’s efficiency and its practical applications in real-world scenarios. By working on Python projects, developers gain firsthand experience in leveraging Python’s capabilities to build sophisticated web applications that meet the demands of modern users and businesses alike.

  1. Password Generator:

The provided Python script creates a random password of a specified length. It relies on the random and string modules to select characters randomly from a pool comprising letters, digits, and punctuation symbols. After the user inputs the desired length, the program displays the generated password. Copy the code paste it in your editor and try it yourself.

import random 

import string

def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password

password_length = int(input("Enter the length of the password: "))
generated_password = generate_password(password_length)
print("Generated password:", generated_password)

Explanation:

  1. The random and string modules are imported. The random module is used to generate random values, while the string module provides strings containing ASCII characters of lowercase and uppercase letters, digits, and punctuation symbols.
  2. A function named generate_password(length) is defined. This function takes a parameter length, which specifies the desired length of the password.
  3. Inside the generate_password function:
    • A string named characters is created by concatenating the strings string.ascii_letters, string.digits, and string.punctuation. This string contains all the characters from which the password will be composed.
    • The random.choice() function randomly selects characters from the characters string. This process is repeated length times using a list comprehension (for _ in range(length)), and the selected characters are joined together using the join() method to form the password string.
    • The generated password is returned by the function.
  4. The program prompts the user to enter the desired length of the password using the input() function. The input is converted to an integer using int() and stored in the variable password_length.
  5. The generate_password function is called with password_length as the argument, and the generated password is stored in the variable generated_password.
  6. Finally, the generated password is printed to the console along with a message indicating that it is the generated password.

2. Todo list:

This program defines a TodoList class that represents a simple to-do list. The class has several methods to add, remove, display, and clear tasks within the list.

class TodoList:

def __init__(self):
self.tasks = []

def add_task(self, task):
self.tasks.append(task)

def remove_task(self, task):
if task in self.tasks:
self.tasks.remove(task)

def show_tasks(self):
print("Todo List:")
for index, task in enumerate(self.tasks):
print(f"{index + 1}. {task}")

def clear_tasks(self):
self.tasks = []

# Usage
todo_list = TodoList()
todo_list.add_task("Task 1")
todo_list.add_task("Task 2")
todo_list.show_tasks()
todo_list.remove_task("Task 2")
todo_list.show_tasks()
todo_list.clear_tasks()
todo_list.show_tasks()

3. Fibonacci Series Generator

Let’s generates a Fibonacci sequence of numbers up to a given count n. The program defines a function called generate_fibonacci_sequence that takes n as an argument.

def generate_fibonacci_sequence(n):

sequence = [0, 1]

if n <= 2:
return sequence[:n]

while len(sequence) < n:
next_number = sequence[-1] + sequence[-2]
sequence.append(next_number)

return sequence

# Usage
n = int(input("Enter the number of Fibonacci numbers to generate: "))
fibonacci_sequence = generate_fibonacci_sequence(n)
print("Fibonacci Sequence:", fibonacci_sequence)

3. Music Player:

Lets take a the Pygame library to play music from a file. It defines a function called play_music that takes a file path as an argument. The function initializes the Pygame library and the mixer module for audio playback. It then loads the specified music file using pygame.mixer.music.load and starts playing the music using pygame.mixer.music.play.

import pygame


def play_music(file_path):
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()

# Usage
file_path = "music.mp3"
play_music(file_path)

4. Web Scraping Tool:

This program utilizes the BeautifulSoup library to extract information from websites. It’s capable of scraping data from web pages, allowing users to save it for subsequent analysis or presentation purposes.

import requests

from bs4 import BeautifulSoup

def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# Example: scraping titles and links of articles from a news website
articles = soup.select('.article')
if articles:
for article in articles:
title = article.select_one('.title').text.strip()
link = article.select_one('.link')['href']
print(f"Title: {title}\nLink: {link}\n")
else:
print("No articles found on the page.")

# Usage
url = "https://www.example.com" #replace with your URL
scrape_website(url)

5. Image Processor:

This application is a web-based image processing tool built with Flask and Pillow. It enables users to perform various image manipulation tasks such as resizing, filtering, cropping, and adding effects.

from flask import Flask, request, send_file

from PIL import Image

app = Flask(__name__)

@app.route('/process-image', methods=['POST'])
def process_image():
image_file = request.files['image']

# Load the image using Pillow
image = Image.open(image_file)

# Perform desired image processing tasks
# Example: resizing the image to a specific size
resized_image = image.resize((800, 600))

# Save the processed image
processed_image_path = 'processed_image.jpg' # repalce the path of the image with yours
resized_image.save(processed_image_path)

return send_file(processed_image_path, mimetype='image/jpeg')

# Usage
if __name__ == '__main__':
app.run()

6. Web Based Dashboard:

This is a dashboard created with Flask and Plotly, designed to operate on the web. It’s capable of retrieving data from databases or APIs and presenting it through charts, graphs, or interactive visualizations.

from flask import Flask, render_template

import plotly.graph_objects as go

app = Flask(__name__)

@app.route('/dashboard')
def dashboard():
# Fetch data from a database or external API
# Example: creating a bar chart of sales data
sales_data = {'Product A': 1000, 'Product B': 1500, 'Product C': 800}
products = list(sales_data.keys())
sales = list(sales_data.values())

# Create a bar chart using Plotly
fig = go.Figure(data=go.Bar(x=products, y=sales))
chart_div = fig.to_html(full_html=False)

return render_template('dashboard.html', chart_div=chart_div)

# Usage
if __name__ == '__main__':
app.run()

7. RESTful API

Let’s create a RESTful API using Flask, a web framework. This program can provide data and functionalities to other applications or websites through API endpoints.

from flask import Flask, jsonify


app = Flask(__name__)

@app.route('/api/data', methods=['GET'])
def get_data():
# Retrieve data from a database or external source
data = {'key': 'value'}
return jsonify(data)

# Usage
if __name__ == '__main__':
app.run()

8. Alarm Clock in Python with GUI

from time import strftime 

from tkinter import *

import time
import datetime
from pygame import mixer

root = Tk()
root.title('Alarm-Clock')

def setalarm():
alarmtime=f"{hrs.get()}:{mins.get()}:{secs.get()}"
print(alarmtime)
if(alarmtime!="::"):
alarmclock(alarmtime)

def alarmclock(alarmtime):
while True:
time.sleep(1)
time_now=datetime.datetime.now().strftime("%H:%M:%S")
print(time_now)
if time_now==alarmtime:
Wakeup=Label(root, font = ('arial', 20, 'bold'),
text="Wake up!",bg="DodgerBlue2",fg="white").grid(row=6,columnspan=3)
print("wake up!")
mixer.init()
mixer.music.load(r'C:/Users/Swarna/Desktop/MyPlaylist/WakeUP.mp3') # user your own path
mixer.music.play()
break


hrs=StringVar()
mins=StringVar()
secs=StringVar()

greet=Label(root, font = ('arial', 20, 'bold'),
text="Set Your Alarm !").grid(row=1,columnspan=3)

hrbtn=Entry(root,textvariable=hrs,width=5,font =('arial', 20, 'bold'))
hrbtn.grid(row=2,column=1)

minbtn=Entry(root,textvariable=mins,
width=5,font = ('arial', 20, 'bold')).grid(row=2,column=2)

secbtn=Entry(root,textvariable=secs,
width=5,font = ('arial', 20, 'bold')).grid(row=2,column=3)

setbtn=Button(root,text="set alarm",command=setalarm,bg="DodgerBlue2",
fg="white",font = ('arial', 20, 'bold')).grid(row=4,columnspan=3)

timeleft = Label(root,font=('arial', 20, 'bold'))
timeleft.grid()

mainloop()

Explanation of Function Used:

  1. SetAlarm: This function is responsible for setting an alarm. It invokes the alarmClock method by passing the desired alarm time as an argument, provided that the user has entered a correct and non-empty time.
  2. alarmClock: This function carries out several critical tasks:a. It captures the current time and stores it in the variable time_now in a specified format (“%H:%M:%S”).b. It compares the current time with the specified alarm time. If the current time matches the alarm time, it triggers a wake-up message and initiates the alarm sound using the Pygame library and mixer module. If the current time doesn’t match the alarm time, the function waits for one second before repeating the comparison and continuing the process.
  3. Hrs, Mins, Secs: They are tkinter string variables that store the hour’s, minute’s and second’s value entered by the user before setting an alarm.

9. Block Website:

import tkinter as tk

import time
from datetime import datetime as dt

# Function to block websites
def block_websites():
# Define the path to the hosts file
hosts_path = r"C:\Windows\System32\drivers\etc\hosts" # Change this path accordingly

# Get the list of websites to block from the entry widget
websites = entry.get().split(",")

# IP address to redirect the blocked websites
redirect_ip = "127.0.0.1"

# Check if the current time is within the block period (e.g., from 8 AM to 4 PM)
if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
print("Working hours...")
with open(hosts_path, "r+") as file:
content = file.read()
for website in websites:
if website.strip() in content:
pass
else:
file.write(redirect_ip + " " + website.strip() + "\n")
else:
print("Fun hours...")
with open(hosts_path, "r+") as file:
content = file.readlines()
file.seek(0)
for line in content:
if not any(website.strip() in line for website in websites):
file.write(line)
file.truncate()

# Create a GUI window
root = tk.Tk()
root.title("Website Blocker")

# Label
label = tk.Label(root, text="Enter websites to block (separated by comma):")
label.pack()

# Entry widget to enter websites
entry = tk.Entry(root, width=50)
entry.pack()

# Button to block websites
button = tk.Button(root, text="Block Websites", command=block_websites)
button.pack()

root.mainloop()

This code creates a simple Tkinter GUI window where the user can enter the websites to block in the entry widget separated by commas. When the user clicks the “Block Websites” button, the block_websites function is called, which blocks the specified websites according to the time conditions.

Output:

Explanation of above code:

  1. Import Statements:
    • import tkinter as tk: Imports the tkinter library, which is used for creating the GUI.
    • import time: Imports the time module for adding delays.
    • from datetime import datetime as dt: Imports the datetime class from the datetime module and aliases it as dt.
  2. block_websites Function:
    • This function blocks the specified websites according to the time conditions.
    • It first retrieves the list of websites to block from the entry widget (entry) by splitting the input text based on commas.
    • Then, it checks if the current time is within the specified block period (e.g., from 8 AM to 4 PM).
    • If it’s within the block period, the function opens the system’s hosts file (hosts_path), reads its content, and appends the IP address (redirect_ip) followed by the websites to block.
    • If it’s not within the block period, the function reads the hosts file, removes any lines containing the specified websites, and writes back the modified content.
  3. GUI Creation:
    • It creates a GUI window (root) using Tkinter.
    • A label (label) is added to indicate where to enter the websites.
    • An entry widget (entry) is provided for the user to input the websites to block, separated by commas.
    • A button (button) is added to trigger the blocking of websites when clicked. The block_websites function is bound to this button.
  4. Tkinter Main Loop:
    • The root.mainloop() call starts the Tkinter event loop, allowing the GUI to respond to user interactions.

10. Notepad using Python

from tkinter import *

from tkinter import font, filedialog

def saveDoc():
global textarea
text=textarea.get("1.0","end-1c")
location=filedialog.asksaveasfilename()
file=open(location,"w+")
file.write(text)
file.close()

def Algerian():
global textarea
textarea.config(font="Algerian")

def Arial():
global textarea
textarea.config(font="Arial")

def Courier():
global textarea
textarea.config(font="Courier")

def Cambria():
global textarea
textarea.config(font="Cambria")

def boldDoc():
global textarea
textarea.config(font=('arial',14,'bold'))

root=Tk()
root.title("Notepad")

savebtn=Button(root,command=saveDoc,text="Save")
savebtn.grid(row=1,column=0)
savebtn.config(font=('arial',20,'bold'),bg="DodgerBlue2",fg="white")

fontbtn=Menubutton(root,text="Font")
fontbtn.config(font=('arial',20,'bold'),bg="DodgerBlue2",fg="white")
fontbtn.grid(row=1,column=1)
fontbtn.menu=Menu(fontbtn,tearoff=0)
fontbtn["menu"]=fontbtn.menu

fontbtn.menu.add_checkbutton(label="Arial",
command=Arial)

fontbtn.menu.add_checkbutton(label="Algerian",
command=Algerian)

fontbtn.menu.add_checkbutton(label="Cambria",
command=Cambria)

fontbtn.menu.add_checkbutton(label="Courier",
command=Courier)

boldbtn=Button(root,command=boldDoc,text="Bold")
boldbtn.grid(row=1,column=2)
boldbtn.config(font=('arial',20,'bold'),bg="DodgerBlue2",fg="white")

textarea=Text(root)
textarea.grid(row=2,columnspan=5)

# To know or add more font options
# fonts=list(font.families())
# fonts.sort()

mainloop()

11. Text From Image:

from tkinter import *

from tkinter import filedialog
from PIL import ImageTk, Image
import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)//Tesseract-OCR//tesseract.exe'

root = Tk()
root.title('Text Extractor')

newline= Label(root)
uploaded_img=Label(root)
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )


def extract(path):
Actual_image = cv2.imread(path)
Sample_img = cv2.resize(Actual_image,(400,350))
Image_ht,Image_wd,Image_thickness = Sample_img.shape
Sample_img = cv2.cvtColor(Sample_img,cv2.COLOR_BGR2RGB)
texts = pytesseract.image_to_data(Sample_img)
mytext=""
prevy=0
for cnt,text in enumerate(texts.splitlines()):
if cnt==0:
continue
text = text.split()
if len(text)==12:
x,y,w,h = int(text[6]),int(text[7]),int(text[8]),int(text[9])
if(len(mytext)==0):
prey=y
if(prevy-y>=10 or y-prevy>=10):
print(mytext)
Label(root,text=mytext,font=('Times',15,'bold')).pack()
mytext=""
mytext = mytext + text[11]+" "
prevy=y
Label(root,text=mytext,font=('Times',15,'bold')).pack()

def show_extract_button(path):
extractBtn= Button(root,text="Extract text",command=lambda: extract(path),bg="#2f2f77",fg="gray",pady=15,padx=15,font=('Times',15,'bold'))
extractBtn.pack()

def upload():
try:
path=filedialog.askopenfilename()
image=Image.open(path)
img=ImageTk.PhotoImage(image)
uploaded_img.configure(image=img)
uploaded_img.image=img
show_extract_button(path)
except:
pass

uploadbtn = Button(root,text="Upload an image",command=upload,bg="#2f2f77",fg="gray",height=2,width=20,font=('Times',15,'bold')).pack()
newline.configure(text='\n')
newline.pack()
uploaded_img.pack()

root.mainloop()

Output:

Code Explanation:

  1. Imports:
    • from tkinter import *: Imports the entire Tkinter module to create the GUI.
    • from tkinter import filedialog: Imports the filedialog submodule from Tkinter for file selection dialogs.
    • from PIL import ImageTk, Image: Imports classes from the Pillow library for working with images.
    • import cv2: Imports the OpenCV library for image processing.
    • import pytesseract: Imports the Pytesseract library for optical character recognition (OCR).
  2. Setup:
    • pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)//Tesseract-OCR//tesseract.exe': Sets the path to the Tesseract OCR executable.
  3. Tkinter Window Setup:
    • Creates a Tkinter window (root) with the title ‘Text Extractor’.
  4. Function Definitions:
    • extract(path): Function to extract text from the uploaded image using Pytesseract OCR. It reads the image, resizes it, converts it to RGB format, and performs OCR. Extracted text is displayed in the Tkinter window.
    • show_extract_button(path): Function to display the ‘Extract Text’ button after an image is uploaded. It binds the extract function to the button click event.
    • upload(): Function to open a file dialog for selecting an image file. It displays the selected image in the Tkinter window and calls show_extract_button to show the ‘Extract Text’ button.
  5. Button Setup:
    • uploadbtn: Creates a ‘Upload an image’ button which calls the upload function when clicked.
  6. Other Components:
    • newline: Label used for adding spacing between components.
    • uploaded_img: Label used for displaying the uploaded image.
    • scrollbar: Scrollbar widget for scrolling through extracted text.
  7. Main Event Loop:
    • root.mainloop(): Starts the Tkinter event loop to handle user interactions and keep the GUI window open.

These projects mentioned above are helpful for practicing as well as can be used as demo projects in various schools, organizations with your own added features.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>