Component A: Program Code
from flask import request, jsonify, Blueprint
from model.quotesbase import db, Quotes
userquotes = Blueprint('userquotes', __name__)
@userquotes.route('/api/userquotes', methods=['POST'])
def add_user():
# Input from the user (Component A: Input Handling)
data = request.get_json()
author = data.get('author')
quote = data.get('quote')
date = data.get('date')
if not all([author, quote, date]):
return jsonify({'error': 'Missing data'}), 400
new_user = Quotes(author=author, quote=quote, date=date)
db.session.add(new_user)
db.session.commit()
# Output: Confirmation message (Component A: Output Handling)
return jsonify({'message': 'Quote added successfully'}), 201
@userquotes.route('/api/userquotes', methods=['GET'])
def get_quotes():
# List usage: Storing multiple quotes (Component A: Data Abstraction)
quotes = Quotes.query.all()
result = [
{
'id': quote.id,
'author': quote._author,
'quote': quote._quote,
'date': quote._date
}
for quote in quotes
]
return jsonify(result), 200
@userquotes.route('/api/userquotes/<int:id>', methods=['DELETE'])
def delete_quote(id):
quote = Quotes.query.get(id)
if not quote:
return jsonify({'error': 'Quote not found'}), 404
db.session.delete(quote)
db.session.commit()
return jsonify({'message': 'Quote deleted successfully'}), 200
@userquotes.route('/api/userquotes/<int:id>', methods=['PUT'])
def update_quote(id):
data = request.get_json()
author = data.get('author')
quote = data.get('quote')
date = data.get('date')
if not all([author, quote, date]):
return jsonify({'error': 'Missing data'}), 400
existing_quote = Quotes.query.get(id)
if not existing_quote:
return jsonify({'error': 'Quote not found'}), 404
# Procedure: Updating an existing quote (Component A: Student-Developed Procedure)
existing_quote._author = author
existing_quote._quote = quote
existing_quote._date = date
db.session.commit()
return jsonify({'message': 'Quote updated successfully'}), 200
Key Aspects
1. Input Handling
- Function:
add_user()
- Process:
- Receives JSON data from a POST request.
- Extracts
author
,quote
, anddate
from user input. - Checks for missing data and returns an error if any field is empty.
- Saves the new quote to the database and returns a confirmation message.
2. Data Abstraction
- Function:
get_quotes()
- Process:
- Retrieves all quotes from the database.
- Stores the quotes in a list of dictionaries, each containing
id
,author
,quote
, anddate
. - Returns the structured data as a JSON response.
3. Output Handling
- Functions:
add_user()
: Returns a success message when a quote is added.delete_quote(id)
: Returns a confirmation message when a quote is deleted.update_quote(id)
: Returns a success message after modifying a quote.
4. Student-Developed Procedure
- Function:
update_quote(id)
- Process:
- Receives JSON data and extracts updated values.
- Checks for missing data and validates if the quote exists.
- Updates the quote’s details and commits the changes to the database.
- Returns a confirmation message after a successful update.
Complexity Management
- Encapsulation: Separates concerns into specific functions for adding, retrieving, updating, and deleting quotes.
- Data Abstraction: Uses lists and dictionaries to organize and retrieve data efficiently.
- Error Handling: Validates input and ensures proper responses for missing or incorrect data.
- Procedure Implementation: The
update_quote
function follows structured steps to modify and persist quote data.
Component B: VIDEO
Demonstrates:
- Input to your program
- At least one aspect of the functionality of your program
- Output produced by your program
Requirements Followed:
- Either .webm, .mp4, .wmv, .avi, or .mov format
- No more than 1 minute in length
- No more than 30MB in file size
Component C: PERSONALIZED PROJECT REFERENCE (PPR)
Student-Developed Procedure
Procedure: Capture and paste two program code segments you developed during the administration of this task that contain a student-developed procedure that implements an algorithm used in your program and a call to that procedure.
Segment 1: Procedure Definition (with sequencing, selection)
def update_quote(id, author, quote, date):
"""
Updates an existing quote in the database.
Args:
id (int): The ID of the quote to update.
author (str): The new author name.
quote (str): The new quote text.
date (str): The new date of the quote.
"""
existing_quote = Quotes.query.get(id)
if not existing_quote: # Selection (if condition)
return {'error': 'Quote not found'}
# Sequencing (steps executed in order)
existing_quote._author = author
existing_quote._quote = quote
existing_quote._date = date
db.session.commit()
return {'message': 'Quote updated successfully'}
Segment 2: Calling the Procedure
function editQuote(id, currentAuthor, currentQuote, currentDate) {
document.getElementById('quote-edit-form').style.display = 'block';
document.getElementById('quote-form').style.display = 'none'; // Hide the Add form
document.getElementById('edit-author').placeholder = currentAuthor;
document.getElementById('edit-quote').placeholder = currentQuote;
document.getElementById('edit-date').placeholder = currentDate;
document.getElementById('edit-author').value = "";
document.getElementById('edit-quote').value = "";
document.getElementById('edit-date').value = "";
const form = document.getElementById('edit-quote-form');
form.onsubmit = async function(event) {
event.preventDefault();
const author = document.getElementById('edit-author').value || currentAuthor;
const quote = document.getElementById('edit-quote').value || currentQuote;
const date = document.getElementById('edit-date').value || currentDate;
const response = await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ author, quote, date }),
});
if (response.ok) {
alert('Notes updated successfully!');
fetchQuotes();
cancelEdit();
} else {
alert('Failed to update notes.');
}
};
}
Key Aspects
Segment 1: Procedure Definition (with Sequencing and Selection)
- Function:
update_quote(id, author, quote, date)
- Purpose: Updates an existing quote in the database.
- Selection: Uses an
if
condition to check if the quote exists before updating. - Sequencing: Executes steps in order: retrieving the quote, modifying its attributes, committing changes to the database, and returning a success message.
- Problems: Next time I should find a procedure with iteration. I couldn’t find any procedure in my API code that had Sequencing, Selection, and Iteration but I will try to find
Segment 2: Calling the Procedure
- Function:
editQuote(id, currentAuthor, currentQuote, currentDate)
- Purpose: Handles the frontend logic for editing a quote and sends a
PUT
request to update the quote in the backend. - User Interaction:
- Displays the edit form and hides the add form.
- Sets placeholders with the current quote details.
- Allows user input while keeping previous values if fields are left empty.
- Procedure Call:
- When the form is submitted, an asynchronous
fetch
request is sent to call theupdate_quote
function in the backend. - If the request succeeds, the UI is updated and refreshed.
- When the form is submitted, an asynchronous
Complexity Management
- Encapsulation: The update logic is handled in a single procedure, reducing redundancy.
- Selection: Ensures only existing quotes are updated, preventing errors.
- Sequencing: Steps are executed in a structured manner for consistency.
- Frontend-Backend Communication: The procedure is effectively called via a
PUT
request, ensuring seamless updates between the database and the user interface.
List Usage for Managing Complexity
List: Capture and paste two program code segments you developed during the administration of this task that contain a list (or other collection type) being used to manage complexity in your program.
Segment 3: Storing Data in a List
quotes = Quotes.query.all() # Retrieving all quotes
result = [ # Using a list to store multiple quotes
{
'id': quote.id,
'author': quote._author,
'quote': quote._quote,
'date': quote._date
}
for quote in quotes # Iteration over the list of quotes
]
Segment 4: Using Data from the List
@app.route('/api/userquotes/random', methods=['GET'])
def get_random_quote():
quotes = Quotes.query.all()
if not quotes: # Selection: checking if the list is empty
return jsonify({'error': 'No quotes available'}), 404
random_quote = random.choice(quotes) # Using list data to select a random quote
return jsonify({
'id': random_quote.id,
'author': random_quote._author,
'quote': random_quote._quote,
'date': random_quote._date
}), 200
Key Aspects
Segment 3: Storing Data in a List
- Retrieves all quotes from a database using
Quotes.query.all()
. - Iterates over the retrieved data to store it in a list of dictionaries, each containing details about a quote (ID, author, text, and date).
- This structure simplifies data handling by allowing easy access and manipulation.
Segment 4: Using Data from the List
- Defines an API endpoint
/api/userquotes/random
. - Retrieves all quotes from the database and checks if the list is empty (selection).
- Uses
random.choice()
to select a random quote from the list. - Returns the selected quote in JSON format, making the data easily accessible via API.
Complexity Management
- The list efficiently organizes multiple quotes for retrieval and processing.
- Iteration and selection simplify accessing and manipulating the data.
- Random selection enhances user experience by dynamically retrieving different quotes.