Skip to the content.

Personal Feature Blog

Database Feature

Study Buddy

StudyBuddy is an interactive platform built to support students throughout their academic journey. Whether you’re mastering math, exploring science, diving into history, or studying any other subject, StudyBuddy is here to help you excel. Our mission is to make learning enjoyable, engaging, and effective. With a wide range of tools at your disposal, StudyBuddy provides a well-rounded study experience.

Quote Manager

The Quote Manager feature allows users to store, edit, and delete quotes in a database. It provides a user-friendly interface with a dynamic table displaying quotes, authors, and dates. Every row in the datatable includes a quote with its respective author and date. The backend API handles all interactions using GET, POST, PUT, and DELETE methods, ensuring seamless data management. GET

JavaScript Methods in the Quote Management App

This script manages user quotes through CRUD (Create, Read, Update, Delete) operations using a REST API.
Data is sent and received in JSON (JavaScript Object Notation) format.

1. fetchQuotes()

  • Purpose: Fetches and displays quotes from the API.
  • Process:
    • Sends a GET request to API_URL.
    • Parses the JSON response containing an array of quotes.
    • Iterates through the quotes and dynamically updates the HTML table.
    • Each row includes an “Edit” and “Delete” button.

2. addQuote(event)

  • Purpose: Adds a new quote to the database.
  • Process:
    • Prevents form default submission with event.preventDefault().
    • Reads input values (author, quote, date).
    • Converts data into a JSON object and sends a POST request.
    • If successful, the new quote is added, and the form is reset.

3. deleteQuote(id)

  • Purpose: Deletes a quote based on its ID.
  • Process:
    • Sends a DELETE request to remove the quote.
    • If successful, the user is alerted, and fetchQuotes() refreshes the table.

4. editQuote(id, currentAuthor, currentQuote, currentDate)

  • Purpose: Prepares the form to edit an existing quote.
  • Process:
    • Switches from “Add” mode to “Edit” mode.
    • Pre-fills the form fields with the current quote’s data.
    • Overrides form submission to send an updated JSON object via a PUT request.

5. cancelEdit()

  • Purpose: Cancels the edit mode and returns to the add form.
  • Process:
    • Hides the edit form and shows the add form.
    • Resets the edit form fields.

6. init()

  • Purpose: Initializes the app on page load.
  • Process:
    • Attaches the addQuote() function to the form’s submit event.
    • Calls fetchQuotes() to load existing quotes.

7. DOMContentLoaded Event Listener

  • Ensures init() runs after the document is fully loaded.

JSON Usage in This Script

  • Sending Data: Quotes are converted into a JSON object (JSON.stringify({ author, quote, date })) before sending via POST or PUT requests.
  • Receiving Data: The server response is parsed as JSON (await response.json()) to dynamically update the UI.
  • API Communication: The script uses fetch API to interact with a backend that processes and stores JSON-formatted quotes.

API for Quote Management

This API handles CRUD (Create, Read, Update, Delete) operations for user quotes.
Data is exchanged in JSON format, and jsonify is used to return JSON responses.

1. @userquotes.route('/api/userquotes', methods=['POST'])

  • Purpose: Adds a new quote to the database.
  • Process:
    • Retrieves JSON data from the request using request.get_json().
    • Extracts author, quote, and date fields.
    • Returns an error if any required field is missing (400 Bad Request).
    • Creates a new Quotes object and adds it to the database.
    • Uses jsonify() to return a success message in JSON format (201 Created).

2. @userquotes.route('/api/userquotes', methods=['GET'])

  • Purpose: Retrieves all quotes from the database.
  • Process:
    • Queries all quotes from the Quotes table.
    • Converts each quote object into a JSON-compatible dictionary.
    • Uses jsonify() to return a list of dictionaries with the id, quote, author, and date (200 OK). GET

3. @userquotes.route('/api/userquotes/<int:id>', methods=['DELETE'])

  • Purpose: Deletes a quote by its ID.
  • Process:
    • Searches for the quote using Quotes.query.get(id).
    • If the quote doesn’t exist, returns a JSON error (404 Not Found).
    • If found, deletes it from the database and commits changes.
    • Uses jsonify() to return a success message (200 OK). DELETE

4. @userquotes.route('/api/userquotes/<int:id>', methods=['PUT'])

  • Purpose: Updates an existing quote by ID.
  • Process:
    • Retrieves JSON data using request.get_json().
    • Extracts author, quote, and date fields.
    • If any field is missing, returns a JSON error (400 Bad Request).
    • Searches for the existing quote in the database.
    • If the quote is not found, returns a JSON error (404 Not Found).
    • Updates the quote’s fields and commits the changes.
    • Uses jsonify() to return a success message (200 OK). PUT

Backend: Database Model and Initialization

The backend uses Flask-SQLAlchemy to define and manage a database table for storing quotes. The Quotes class represents a database model, and the initquotes() function initializes the table with sample data.

1. Quotes Model

The Quotes class is a database table for storing user quotes. It has the following attributes:

  • id: A unique identifier (Primary Key).
  • _author: The name of the person who said the quote.
  • _quote: The actual quote text.
  • _date: The year the quote was said.

The model also includes methods for CRUD (Create, Read, Update, Delete) operations, making it easy to manage quotes.

2. Database Initialization with initquotes()

The function initquotes() ensures that the database is properly set up and pre-populated with quotes.

How It Works

  1. Calls db.create_all() to create the user_quotes table if it doesn’t exist.
  2. Adds predefined quotes (e.g., from Albert Einstein, Gandhi).
  3. Uses .create() method to insert them into the database.
  4. Handles errors like duplicate entries using IntegrityError.

🚀 Sequencing, Selection, and Iteration in the Quotes Class

Sequencing

🔹 Example from Quotes Class:

def create(self):
    try:
        db.session.add(self)  # Step 1: Add the quote to the database
        db.session.commit()   # Step 2: Commit the changes
    except Exception as e:
        db.session.rollback()  # Step 3: Rollback if there's an error
        raise e
@staticmethod

Selection

🔹 Example from Quotes Class:

def restore(data):
    for sbuser_data in data:
        author = sbuser_data.get("author", None)
        sbuser = Quotes.query.filter_by(_author=author).first()

        if sbuser:  # Selection: If the quote exists, update it
            sbuser.update(sbuser_data)
        else:       # Otherwise, create a new quote entry
            sbuser = Quotes(**sbuser_data)
            sbuser.update(sbuser_data)
            sbuser.create()

Iteration

🔹 Example from Quotes Class:

@staticmethod
def restore(data):
    for sbuser_data in data:  # Iterating through each quote in the data
        author = sbuser_data.get("author", None)
        sbuser = Quotes.query.filter_by(_author=author).first()

        if sbuser:
            sbuser.update(sbuser_data)
        else:
            sbuser = Quotes(**sbuser_data)
            sbuser.update(sbuser_data)
            sbuser.create()

🎯 How This Connects to CollegeBoard AP CSP Big Idea 1 (Creative Development)

🔹 Big Idea 1: Creative Development focuses on:

✔️ The design and implementation of programs. ✔️ Using sequencing, selection, and iteration to develop functional solutions. ✔️ Collaboration and problem-solving through structured programming.

🔹 How the Quotes Class Fulfills Big Idea 1:

Creative Development

  • The restore() function is designed to efficiently process multiple quotes while avoiding duplicates.
  • Uses logical selection (if-else) and iteration (loops) to manage database operations.

Algorithm Design

  • The combination of sequencing, selection, and iteration ensures smooth execution.
  • The if condition prevents duplicate entries, making the program efficient.

Data Processing

  • The loop iterates over a dataset of quotes, making the function scalable.
  • The selection logic ensures that only necessary updates are made.