Category: projects

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMAVf-0MreWDi9XMI_A_h0luXpLCCnA-o5wA&s

  • Online Quiz and Exam Platform

    Requirements

    • Python 3.x
    • Flask
    • SQLite (for a simple database)
    • HTML/CSS/JavaScript (for the frontend)

    Step 1: Setting Up Your Environment

    First, ensure you have Flask installed. You can do this using pip:

    pip install Flask
    

    Step 2: Create the Flask App

    Create a directory for your project and inside it, create a file named app.py.

    # app.py
    from flask import Flask, render_template, request, redirect, url_for, session
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your_secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quizzes.db'
    db = SQLAlchemy(app)
    
    # Models
    class Quiz(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    quiz_id = db.Column(db.Integer, db.ForeignKey('quiz.id'), nullable=False)
    question_text = db.Column(db.String(200), nullable=False)
    options = db.Column(db.String(500), nullable=False)
    answer = db.Column(db.String(200), nullable=False)
    # Routes @app.route('/') def index():
    quizzes = Quiz.query.all()
    return render_template('index.html', quizzes=quizzes)
    @app.route('/quiz/<int:quiz_id>', methods=['GET', 'POST']) def quiz(quiz_id):
    if request.method == 'POST':
        # Handle quiz submission
        return redirect(url_for('results'))
    quiz = Quiz.query.get_or_404(quiz_id)
    questions = Question.query.filter_by(quiz_id=quiz_id).all()
    return render_template('quiz.html', quiz=quiz, questions=questions)
    @app.route('/results') def results():
    return "Results page"
    if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

    Step 3: Create HTML Templates

    Create a folder named templates in the same directory as your app.py. Inside this folder, create two HTML files: index.html and quiz.html.

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>Quizzes&lt;/title>
    </head> <body>
    &lt;h1>Available Quizzes&lt;/h1>
    &lt;ul>
        {% for quiz in quizzes %}
        &lt;li>&lt;a href="{{ url_for('quiz', quiz_id=quiz.id) }}">{{ quiz.title }}&lt;/a>&lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    quiz.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>{{ quiz.title }}&lt;/title>
    </head> <body>
    &lt;h1>{{ quiz.title }}&lt;/h1>
    &lt;form method="POST">
        {% for question in questions %}
        &lt;div>
            &lt;p>{{ question.question_text }}&lt;/p>
            {% for option in question.options.split(',') %}
            &lt;label>
                &lt;input type="radio" name="question_{{ question.id }}" value="{{ option }}">
                {{ option }}
            &lt;/label>&lt;br>
            {% endfor %}
        &lt;/div>
        {% endfor %}
        &lt;button type="submit">Submit&lt;/button>
    &lt;/form>
    </body> </html>

    Step 4: Populate the Database

    You can use a Python shell or create a separate script to add quizzes and questions to your database. For example:

    from app import db, Quiz, Question
    
    # Create quizzes and questions
    db.create_all()
    
    quiz1 = Quiz(title='Python Basics')
    db.session.add(quiz1)
    db.session.commit()
    
    question1 = Question(quiz_id=1, question_text='What is the output of 2 + 2?', options='3,4,5,6', answer='4')
    db.session.add(question1)
    db.session.commit()
    

    Step 5: Run Your Application

    Now you can run your Flask application:

    python app.py
    

    Step 6: Access the App

    Open your browser and navigate to http://127.0.0.1:5000/. You should see your quiz index page.

    Future Enhancements

    • User authentication (login/signup)
    • Score tracking
    • Timer for quizzes
    • Admin interface for quiz management
    • Frontend improvements with frameworks like React or Vue.js
  • Pet Adoption Platform

    Project Structure

    pet_adoption/
    │
    ├── app.py                # Main application file
    ├── templates/            # HTML templates
    │   ├── index.html
    │   ├── add_pet.html
    │   └── pet_details.html
    ├── static/               # Static files (CSS, JS, images)
    │   └── styles.css
    └── pets.db               # SQLite database
    

    Step 1: Set Up the Environment

    1. Install Flask:bashCopy codepip install Flask
    2. Set up SQLite (it usually comes with Python, but you can install it if necessary):bashCopy codepip install sqlite3

    Step 2: Create the Database

    Create a file named database.py to set up the SQLite database:

    import sqlite3
    
    def init_db():
    
    conn = sqlite3.connect('pets.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS pets (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            breed TEXT NOT NULL,
            age INTEGER NOT NULL,
            description TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()
    if __name__ == '__main__':
    init_db()

    Run this file once to create the database.

    Step 3: Create the Main Application

    Create a file named app.py:

    from flask import Flask, render_template, request, redirect
    import sqlite3
    
    app = Flask(__name__)
    
    # Database helper functions
    def get_db_connection():
    
    conn = sqlite3.connect('pets.db')
    conn.row_factory = sqlite3.Row
    return conn
    @app.route('/') def index():
    conn = get_db_connection()
    pets = conn.execute('SELECT * FROM pets').fetchall()
    conn.close()
    return render_template('index.html', pets=pets)
    @app.route('/add', methods=('GET', 'POST')) def add_pet():
    if request.method == 'POST':
        name = request.form&#91;'name']
        breed = request.form&#91;'breed']
        age = request.form&#91;'age']
        description = request.form&#91;'description']
        conn = get_db_connection()
        conn.execute('INSERT INTO pets (name, breed, age, description) VALUES (?, ?, ?, ?)',
                     (name, breed, age, description))
        conn.commit()
        conn.close()
        return redirect('/')
    
    return render_template('add_pet.html')
    @app.route('/pet/<int:pet_id>') def pet_details(pet_id):
    conn = get_db_connection()
    pet = conn.execute('SELECT * FROM pets WHERE id = ?', (pet_id,)).fetchone()
    conn.close()
    return render_template('pet_details.html', pet=pet)
    if __name__ == '__main__':
    app.run(debug=True)

    Step 4: Create HTML Templates

    1. templates/index.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    &lt;title>Pet Adoption&lt;/title>
    </head> <body>
    &lt;h1>Pet Adoption Platform&lt;/h1>
    &lt;a href="/add">Add a Pet&lt;/a>
    &lt;h2>Available Pets&lt;/h2>
    &lt;ul>
        {% for pet in pets %}
            &lt;li>
                &lt;a href="{{ url_for('pet_details', pet_id=pet&#91;'id']) }}">{{ pet&#91;'name'] }} ({{ pet&#91;'breed'] }})&lt;/a>
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    2. templates/add_pet.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Add a Pet&lt;/title>
    </head> <body>
    &lt;h1>Add a Pet&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>&lt;br>
        &lt;input type="text" name="name" required>&lt;br>
        &lt;label>Breed:&lt;/label>&lt;br>
        &lt;input type="text" name="breed" required>&lt;br>
        &lt;label>Age:&lt;/label>&lt;br>
        &lt;input type="number" name="age" required>&lt;br>
        &lt;label>Description:&lt;/label>&lt;br>
        &lt;textarea name="description" required>&lt;/textarea>&lt;br>
        &lt;input type="submit" value="Add Pet">
    &lt;/form>
    </body> </html>

    3. templates/pet_details.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>{{ pet&#91;'name'] }}&lt;/title>
    </head> <body>
    &lt;h1>{{ pet&#91;'name'] }}&lt;/h1>
    &lt;p>Breed: {{ pet&#91;'breed'] }}&lt;/p>
    &lt;p>Age: {{ pet&#91;'age'] }} years&lt;/p>
    &lt;p>Description: {{ pet&#91;'description'] }}&lt;/p>
    &lt;a href="/">Back to Home&lt;/a>
    </body> </html>

    Step 5: Create a CSS File

    Create a file named static/styles.css for basic styling:

    body {
    
    font-family: Arial, sans-serif;
    margin: 20px;
    } h1 {
    color: #333;
    } a {
    text-decoration: none;
    color: blue;
    } ul {
    list-style-type: none;
    padding: 0;
    }

    Step 6: Run the Application

    1. Initialize the database:bashCopy codepython database.py
    2. Run the Flask app:
    python app.py
    1. Open your browser and go to http://127.0.0.1:5000/.
  • Travel Planner

    Simple Travel Planner in Python

    class TravelPlanner:
    
    def __init__(self):
        self.destinations = {}
    
    def add_destination(self, name, activities):
        self.destinations&#91;name] = activities
    
    def view_destinations(self):
        print("Available Destinations:")
        for destination in self.destinations:
            print(f"- {destination}")
    def create_itinerary(self, destination, budget):
        if destination not in self.destinations:
            print("Destination not found.")
            return
        
        activities = self.destinations&#91;destination]
        itinerary = &#91;]
        
        print(f"\nCreating itinerary for {destination} with a budget of ${budget}:")
        
        for activity, cost in activities.items():
            if cost &lt;= budget:
                itinerary.append(activity)
                budget -= cost
                print(f"Added: {activity} (${cost})")
        
        if not itinerary:
            print("No activities fit within the budget.")
        else:
            print("\nFinal Itinerary:")
            for item in itinerary:
                print(f"- {item}")
    # Example Usage if __name__ == "__main__":
    planner = TravelPlanner()
    
    # Adding destinations and their activities
    planner.add_destination("Paris", {
        "Eiffel Tower Visit": 25,
        "Louvre Museum": 15,
        "Seine River Cruise": 30,
        "Notre Dame Cathedral": 0,
        "Montmartre Tour": 10
    })
    
    planner.add_destination("New York", {
        "Statue of Liberty": 20,
        "Broadway Show": 100,
        "Central Park": 0,
        "Museum of Modern Art": 25,
        "Brooklyn Bridge Walk": 0
    })
    
    # Viewing available destinations
    planner.view_destinations()
    
    # Creating an itinerary
    destination = input("\nEnter your destination: ")
    budget = int(input("Enter your budget: "))
    
    planner.create_itinerary(destination, budget)

    How to Use the Code

    1. Add Destinations: You can add destinations and their associated activities with costs.
    2. View Destinations: The program displays all available destinations.
    3. Create Itinerary: Enter a destination and budget to generate a list of activities that fit within your budget.

    Running the Code

    You can run this code in any Python environment. Just copy and paste it into a .py file or directly into a Python interpreter.

    Next Steps

    • Expand Activities: Include more detailed activity descriptions, timings, etc.
    • User Profiles: Allow users to save and load their travel preferences.
    • Web Integration: Create a web app using frameworks like Flask or Django for a more user-friendly interface.
  • Custom URL Shortener

    Prerequisites

    Make sure you have Python installed, along with Flask and SQLite. You can install Flask via pip:

    pip install Flask
    

    Step 1: Set Up the Project Structure

    Create a directory for your project, for example, url_shortener. Inside this directory, create the following files:

    • app.py
    • database.db (this will be created automatically)
    • templates/
      • index.html
      • result.html

    Step 2: Create the Flask App (app.py)

    Here’s a simple Flask app to handle URL shortening:

    from flask import Flask, request, redirect, render_template
    import sqlite3
    import string
    import random
    
    app = Flask(__name__)
    
    # Database setup
    def init_db():
    
    with sqlite3.connect('database.db') as conn:
        conn.execute('''
            CREATE TABLE IF NOT EXISTS urls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                short_url TEXT UNIQUE,
                original_url TEXT NOT NULL
            )
        ''')
    conn.close()
    # Generate a random string def generate_short_url(length=6):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))
    # Route for the homepage @app.route('/') def index():
    return render_template('index.html')
    # Route to shorten the URL @app.route('/shorten', methods=['POST']) def shorten():
    original_url = request.form&#91;'url']
    short_url = generate_short_url()
    with sqlite3.connect('database.db') as conn:
        conn.execute('INSERT INTO urls (short_url, original_url) VALUES (?, ?)', (short_url, original_url))
    conn.close()
    return render_template('result.html', short_url=short_url)
    # Route to redirect to the original URL @app.route('/<short_url>') def redirect_to_url(short_url):
    with sqlite3.connect('database.db') as conn:
        cursor = conn.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
        row = cursor.fetchone()
    conn.close()
    if row:
        return redirect(row&#91;0])
    else:
        return 'URL not found', 404
    if __name__ == '__main__':
    init_db()
    app.run(debug=True)

    Step 3: Create the HTML Templates

    templates/index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>URL Shortener&lt;/title>
    </head> <body>
    &lt;h1>URL Shortener&lt;/h1>
    &lt;form action="/shorten" method="POST">
        &lt;input type="text" name="url" placeholder="Enter URL" required>
        &lt;button type="submit">Shorten&lt;/button>
    &lt;/form>
    </body> </html>

    templates/result.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Shortened URL&lt;/title>
    </head> <body>
    &lt;h1>Your Shortened URL&lt;/h1>
    &lt;p>&lt;a href="{{ short_url }}">{{ request.url_root }}{{ short_url }}&lt;/a>&lt;/p>
    &lt;a href="/">Shorten another URL&lt;/a>
    </body> </html>

    Step 4: Run the Application

    In your terminal, navigate to your project directory and run:

    python app.py
    

    Step 5: Access the Application

    Open your web browser and go to http://127.0.0.1:5000/. You should see the URL shortener interface. Enter a URL, and it will provide you with a shortened version.

  • Photo Gallery Website

    Project Structure

    photo-gallery/
    ├── index.html
    ├── styles.css
    └── script.js
    

    1. index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="styles.css">
    &lt;title>Photo Gallery&lt;/title>
    </head> <body>
    &lt;div class="gallery">
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 1">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 2">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 3">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 4">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 5">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 6">
        &lt;/div>
    &lt;/div>
    &lt;div class="modal" id="modal">
        &lt;span class="close" id="close">&amp;times;&lt;/span>
        &lt;img class="modal-content" id="modal-img">
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    2. styles.css

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    } .gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 20px;
    } .gallery-item {
    flex: 1 1 calc(33.333% - 10px);
    cursor: pointer;
    } .gallery-item img {
    width: 100%;
    border-radius: 8px;
    transition: transform 0.3s;
    } .gallery-item img:hover {
    transform: scale(1.05);
    } .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.8);
    } .modal-content {
    margin: auto;
    display: block;
    max-width: 80%;
    } .close {
    position: absolute;
    top: 20px;
    right: 30px;
    color: white;
    font-size: 40px;
    font-weight: bold;
    cursor: pointer;
    }

    3. script.js

    javascriptCopy codeconst galleryItems = document.querySelectorAll('.gallery-item img');
    const modal = document.getElementById('modal');
    const modalImg = document.getElementById('modal-img');
    const closeModal = document.getElementById('close');
    
    galleryItems.forEach(item => {
    
    item.addEventListener('click', () =&gt; {
        modal.style.display = 'block';
        modalImg.src = item.src;
    });
    }); closeModal.addEventListener('click', () => {
    modal.style.display = 'none';
    }); window.addEventListener('click', (event) => {
    if (event.target === modal) {
        modal.style.display = 'none';
    }
    });

    Instructions

    1. Create the Project Structure: Make a new directory and create the three files listed above.
    2. Copy the Code: Copy the respective code into each file.
    3. Open index.html: Open this file in a web browser to view your photo gallery.
  • Feedback and Survey Tool

    Step 1: Setup the Project

    1. Initialize a new Node.js project:
    mkdir feedback-survey-tool cd feedback-survey-tool npm init -y npm install express body-parser cors
    1. Create the project structure:
    feedback-survey-tool/ ├── server.js ├── public/ │ └── index.html └── package.json

    Step 2: Create the Backend (server.js)

    // server.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    let feedbacks = []; // In-memory storage for feedbacks
    
    app.use(cors());
    app.use(bodyParser.json());
    app.use(express.static('public'));
    
    // Endpoint to submit feedback
    app.post('/api/feedback', (req, res) => {
    
    const feedback = req.body;
    feedbacks.push(feedback);
    res.status(201).json({ message: 'Feedback submitted successfully!' });
    }); // Endpoint to retrieve feedbacks app.get('/api/feedback', (req, res) => {
    res.json(feedbacks);
    }); // Start the server app.listen(PORT, () => {
    console.log(Server is running on http://localhost:${PORT});
    });

    Step 3: Create the Frontend (index.html)

    <!-- public/index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Feedback and Survey Tool&lt;/title>
    &lt;style>
        body { font-family: Arial, sans-serif; }
        form { margin-bottom: 20px; }
        .feedback-list { margin-top: 20px; }
    &lt;/style>
    </head> <body>
    &lt;h1>Feedback and Survey Tool&lt;/h1>
    &lt;form id="feedbackForm">
        &lt;label for="name">Name:&lt;/label>
        &lt;input type="text" id="name" required>
        &lt;br>
        &lt;label for="message">Feedback:&lt;/label>
        &lt;textarea id="message" required>&lt;/textarea>
        &lt;br>
        &lt;button type="submit">Submit Feedback&lt;/button>
    &lt;/form>
    &lt;div class="feedback-list" id="feedbackList">&lt;/div>
    &lt;script>
        const form = document.getElementById('feedbackForm');
        const feedbackList = document.getElementById('feedbackList');
        // Function to submit feedback
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const name = document.getElementById('name').value;
            const message = document.getElementById('message').value;
            const response = await fetch('/api/feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, message })
            });
            if (response.ok) {
                alert('Feedback submitted!');
                form.reset();
                loadFeedbacks();
            }
        });
        // Function to load feedbacks
        async function loadFeedbacks() {
            const response = await fetch('/api/feedback');
            const feedbacks = await response.json();
            feedbackList.innerHTML = feedbacks.map(feedback => 
                &amp;lt;div&gt;&amp;lt;strong&gt;${feedback.name}:&amp;lt;/strong&gt; ${feedback.message}&amp;lt;/div&gt;
            ).join('');
        }
        // Load feedbacks on page load
        loadFeedbacks();
    &lt;/script>
    </body> </html>

    Step 4: Run the Application

    1. Start the server:
    node server.js
    1. Open your browser and go to:
    http://localhost:3000
  • Recipe Meal Planner

    Python Code for Meal Planner

    # Meal Planner Program
    
    def display_meal_plan(meal_plan):
    
    print("\nYour Meal Plan for the Week:")
    for day, meals in meal_plan.items():
        print(f"{day}: Breakfast: {meals&#91;'Breakfast']}, Lunch: {meals&#91;'Lunch']}, Dinner: {meals&#91;'Dinner']}")
    def get_meal_input(day):
    breakfast = input(f"Enter Breakfast for {day}: ")
    lunch = input(f"Enter Lunch for {day}: ")
    dinner = input(f"Enter Dinner for {day}: ")
    return {'Breakfast': breakfast, 'Lunch': lunch, 'Dinner': dinner}
    def meal_planner():
    days_of_week = &#91;'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    meal_plan = {}
    print("Welcome to the Meal Planner!")
    for day in days_of_week:
        meal_plan&#91;day] = get_meal_input(day)
    display_meal_plan(meal_plan)
    if __name__ == "__main__":
    meal_planner()

    How It Works

    1. Function Definitions:
      • display_meal_plan(meal_plan): This function prints the meal plan for the week.
      • get_meal_input(day): This function prompts the user to input meals for breakfast, lunch, and dinner for a given day.
      • meal_planner(): The main function that orchestrates the meal planning process.
    2. User Interaction:
      • The program prompts the user to enter meals for each day of the week.
      • It then stores the meals in a dictionary and displays the entire meal plan at the end.

    Running the Code

    To run this code:

    1. Ensure you have Python installed on your machine.
    2. Copy the code into a Python file (e.g., meal_planner.py).
    3. Run the file using the command: python meal_planner.py.

    Customization Ideas

    • Save and Load Meal Plans: You can extend the program to save meal plans to a file and load them later.
    • Dietary Preferences: Add options for dietary restrictions (e.g., vegetarian, gluten-free).
    • Random Meal Suggestions: Implement a feature that suggests meals from a predefined list.
    • Nutrition Information: Include a database of meals with nutritional information.
  • Volunteer Management System

    Prerequisites

    Make sure you have Python and Flask installed. You can install Flask using pip:

    pip install Flask
    

    Project Structure

    volunteer_management/
    │
    ├── app.py
    ├── templates/
    │   ├── index.html
    │   ├── add_volunteer.html
    │   ├── edit_volunteer.html
    └── database.db
    

    Step 1: Setting Up the Database

    Create a SQLite database and a table for volunteers.

    # db_setup.py
    import sqlite3
    
    def setup_database():
    
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS volunteers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            email TEXT NOT NULL UNIQUE,
            phone TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()
    if __name__ == '__main__':
    setup_database()

    Run this script once to create the database:

    python db_setup.py
    

    Step 2: Create the Flask Application

    Create the main application file app.py:

    from flask import Flask, render_template, request, redirect, url_for
    import sqlite3
    
    app = Flask(__name__)
    
    # Function to get database connection
    def get_db_connection():
    
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn
    # Route to display all volunteers @app.route('/') def index():
    conn = get_db_connection()
    volunteers = conn.execute('SELECT * FROM volunteers').fetchall()
    conn.close()
    return render_template('index.html', volunteers=volunteers)
    # Route to add a new volunteer @app.route('/add', methods=('GET', 'POST')) def add_volunteer():
    if request.method == 'POST':
        name = request.form&#91;'name']
        email = request.form&#91;'email']
        phone = request.form&#91;'phone']
        conn = get_db_connection()
        conn.execute('INSERT INTO volunteers (name, email, phone) VALUES (?, ?, ?)',
                     (name, email, phone))
        conn.commit()
        conn.close()
        return redirect(url_for('index'))
    return render_template('add_volunteer.html')
    # Route to edit a volunteer @app.route('/edit/<int:id>', methods=('GET', 'POST')) def edit_volunteer(id):
    conn = get_db_connection()
    volunteer = conn.execute('SELECT * FROM volunteers WHERE id = ?', (id,)).fetchone()
    if request.method == 'POST':
        name = request.form&#91;'name']
        email = request.form&#91;'email']
        phone = request.form&#91;'phone']
        conn.execute('UPDATE volunteers SET name = ?, email = ?, phone = ? WHERE id = ?',
                     (name, email, phone, id))
        conn.commit()
        conn.close()
        return redirect(url_for('index'))
    conn.close()
    return render_template('edit_volunteer.html', volunteer=volunteer)
    # Route to delete a volunteer @app.route('/delete/<int:id>', methods=('POST',)) def delete_volunteer(id):
    conn = get_db_connection()
    conn.execute('DELETE FROM volunteers WHERE id = ?', (id,))
    conn.commit()
    conn.close()
    return redirect(url_for('index'))
    if __name__ == '__main__':
    app.run(debug=True)

    Step 3: Create HTML Templates

    Create the HTML templates in the templates/ directory.

    index.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Volunteer Management&lt;/title>
    </head> <body>
    &lt;h1>Volunteers&lt;/h1>
    &lt;a href="/add">Add Volunteer&lt;/a>
    &lt;ul>
        {% for volunteer in volunteers %}
            &lt;li>
                {{ volunteer.name }} - {{ volunteer.email }} - {{ volunteer.phone }}
                &lt;a href="/edit/{{ volunteer.id }}">Edit&lt;/a>
                &lt;form action="/delete/{{ volunteer.id }}" method="post" style="display:inline;">
                    &lt;button type="submit">Delete&lt;/button>
                &lt;/form>
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    add_volunteer.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Add Volunteer&lt;/title>
    </head> <body>
    &lt;h1>Add Volunteer&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>
        &lt;input type="text" name="name" required>
        &lt;br>
        &lt;label>Email:&lt;/label>
        &lt;input type="email" name="email" required>
        &lt;br>
        &lt;label>Phone:&lt;/label>
        &lt;input type="text" name="phone" required>
        &lt;br>
        &lt;button type="submit">Add Volunteer&lt;/button>
    &lt;/form>
    </body> </html>

    edit_volunteer.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Edit Volunteer&lt;/title>
    </head> <body>
    &lt;h1>Edit Volunteer&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>
        &lt;input type="text" name="name" value="{{ volunteer.name }}" required>
        &lt;br>
        &lt;label>Email:&lt;/label>
        &lt;input type="email" name="email" value="{{ volunteer.email }}" required>
        &lt;br>
        &lt;label>Phone:&lt;/label>
        &lt;input type="text" name="phone" value="{{ volunteer.phone }}" required>
        &lt;br>
        &lt;button type="submit">Update Volunteer&lt;/button>
    &lt;/form>
    </body> </html>

    Step 4: Run the Application

    You can run the application using:

    python app.py
    

    Access the application in your web browser at http://127.0.0.1:5000/.

  • Subscription-Based Content Platform

    Project Structure

    subscription_platform/
    │
    ├── app.py
    ├── models.py
    ├── templates/
    │   ├── index.html
    │   ├── login.html
    │   ├── signup.html
    │   ├── dashboard.html
    │   └── content.html
    └── static/
    
    └── style.css

    1. Set Up Flask and Dependencies

    Make sure you have Flask and its dependencies installed. You can install them using pip:

    pip install Flask Flask-SQLAlchemy Flask-Login Flask-WTF
    

    2. Create the Models

    In models.py, define the user and content models.

    from flask_sqlalchemy import SQLAlchemy
    from flask_login import UserMixin
    
    db = SQLAlchemy()
    
    class User(db.Model, UserMixin):
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)
    subscription_active = db.Column(db.Boolean, default=False)
    class Content(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(150), nullable=False)
    body = db.Column(db.Text, nullable=False)

    3. Set Up Flask Application

    In app.py, set up your Flask application and routes.

    from flask import Flask, render_template, redirect, url_for, request, flash
    from flask_sqlalchemy import SQLAlchemy
    from flask_login import LoginManager, login_user, login_required, logout_user, current_user
    from models import db, User, Content
    from werkzeug.security import generate_password_hash, check_password_hash
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your_secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
    db.init_app(app)
    login_manager = LoginManager()
    login_manager.init_app(app)
    
    @login_manager.user_loader
    def load_user(user_id):
    
    return User.query.get(int(user_id))
    @app.route('/') def index():
    return render_template('index.html')
    @app.route('/signup', methods=['GET', 'POST']) def signup():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = request.form&#91;'password']
        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(username=username, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        flash('Signup successful! You can now log in.')
        return redirect(url_for('login'))
    return render_template('signup.html')
    @app.route('/login', methods=['GET', 'POST']) def login():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = request.form&#91;'password']
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            login_user(user)
            return redirect(url_for('dashboard'))
        flash('Login failed. Check your credentials.')
    return render_template('login.html')
    @app.route('/dashboard') @login_required def dashboard():
    return render_template('dashboard.html', user=current_user)
    @app.route('/content/<int:content_id>') @login_required def content(content_id):
    content = Content.query.get_or_404(content_id)
    return render_template('content.html', content=content)
    @app.route('/logout') @login_required def logout():
    logout_user()
    return redirect(url_for('index'))
    if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)

    4. Create the HTML Templates

    Create basic templates in the templates folder.

    • index.html:
    <h1>Welcome to the Subscription Platform</h1> <a href="{{ url_for('signup') }}">Sign Up</a> <a href="{{ url_for('login') }}">Login</a>
    • login.html:
    <form method="POST"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Login</button> </form>
    • signup.html:
    <form method="POST"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Sign Up</button> </form>
    • dashboard.html:
    <h1>Hello, {{ user.username }}</h1> <a href="{{ url_for('logout') }}">Logout</a>
    • content.html:
    <h1>{{ content.title }}</h1> <p>{{ content.body }}</p> <a href="{{ url_for('dashboard') }}">Back to Dashboard</a>

    5. CSS for Basic Styling

    You can add a basic CSS file in the static folder to style your application (style.css).

    6. Running the Application

    Make sure you’re in the project directory, then run the Flask application:

    python app.py
    

    Visit http://127.0.0.1:5000/ in your web browser.

    Notes

    • Payment Processing: To implement subscriptions, integrate a payment processor like Stripe or PayPal.
    • Content Management: Expand the app to allow content creation and management by users.
    • Security: Consider enhancing security features (e.g., email verification, password recovery).
    • Deployment: Deploy the application using a platform like Heroku, AWS, or DigitalOcean.

  • Personal Finance Tracker

    Simple Personal Finance Tracker in Python

    First, make sure you have Python installed on your system. You can use any text editor or IDE to write your code.

    Code

    import json
    
    class FinanceTracker:
    
    def __init__(self, filename='finance_data.json'):
        self.filename = filename
        self.load_data()
    def load_data(self):
        try:
            with open(self.filename, 'r') as f:
                self.data = json.load(f)
        except FileNotFoundError:
            self.data = {'income': 0, 'expenses': &#91;], 'balance': 0}
    def save_data(self):
        with open(self.filename, 'w') as f:
            json.dump(self.data, f)
    def add_income(self, amount):
        self.data&#91;'income'] += amount
        self.update_balance()
        self.save_data()
    def add_expense(self, amount, description):
        self.data&#91;'expenses'].append({'amount': amount, 'description': description})
        self.update_balance()
        self.save_data()
    def update_balance(self):
        total_expenses = sum(expense&#91;'amount'] for expense in self.data&#91;'expenses'])
        self.data&#91;'balance'] = self.data&#91;'income'] - total_expenses
    def view_summary(self):
        print(f"Total Income: ${self.data&#91;'income']}")
        print("Expenses:")
        for expense in self.data&#91;'expenses']:
            print(f" - ${expense&#91;'amount']} for {expense&#91;'description']}")
        print(f"Balance: ${self.data&#91;'balance']}")
    def main():
    tracker = FinanceTracker()
    while True:
        print("\nPersonal Finance Tracker")
        print("1. Add Income")
        print("2. Add Expense")
        print("3. View Summary")
        print("4. Exit")
        
        choice = input("Select an option: ")
        if choice == '1':
            amount = float(input("Enter income amount: "))
            tracker.add_income(amount)
        elif choice == '2':
            amount = float(input("Enter expense amount: "))
            description = input("Enter expense description: ")
            tracker.add_expense(amount, description)
        elif choice == '3':
            tracker.view_summary()
        elif choice == '4':
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    How to Run the Code

    The data will be saved in a file named finance_data.json in the same directory, allowing you to track your finances over time.

    Copy the Code: Copy the code above into a new file called finance_tracker.py.

    Run the Script: Open a terminal (or command prompt), navigate to the directory where you saved the file, and run:

    python finance_tracker.py

    Interact with the Tracker:

    Choose options to add income, add expenses, or view your financial summary.