Function
@emotion_api.route('/<title_id>', methods=['GET'])
def get_emotion(title_id):
try:
emotions = Emotion.query.filter_by(title_id=title_id).all()
emotion_data = [
{
'user_id': emo.user_id,
'reaction_type': emo.reaction_type,
'author_id': emo.author_id
}
for emo in emotions
]
return jsonify({
'title_id': title_id,
'emotions': emotion_data
}), 200
except Exception as e:
return jsonify({'error': 'Failed to get reactions', 'message': str(e)}), 500
The get_emotion function is a Flask route that retrieves all reactions for a specific book based on its title_id. Sequencing is shown through the step-by-step process of querying the database and formatting the data. Selection is used in the try-except block, which handles errors and prevents the code from breaking if something goes wrong. Iteration is used in the list comprehension that loops through all reactions (emotions) and formats each one into a dictionary. This allows the function to return a JSON response with the reactions for the selected book.
Call to Function
document.getElementById("fetchEmotionsBtn").addEventListener("click", async function () {
const bookDropdown = document.getElementById("bookDropdown");
const selectedOption = bookDropdown.options[bookDropdown.selectedIndex];
if (!selectedOption.value) {
showStatusMessage('Please select a book first.', false);
return;
}
const bookData = JSON.parse(selectedOption.value);
const titleId = bookData.id;
try {
const response = await fetch(`${pythonURI}/api/emotion/${titleId}`, fetchOptions);
const data = await response.json();
if (!response.ok) throw new Error(data.message || 'Failed to fetch emotions');
displayEmotions(data.emotions);
} catch (error) {
console.error('Error fetching emotions:', error);
showStatusMessage(`Error: ${error.message}`, false);
}
});
The JavaScript function listens for a button click to fetch emotions for a selected book. Sequencing is shown as the code runs step-by-step, first getting the selected book and then making a fetch request. Selection is used in the if statement that checks if the user selected a book and handles errors if the fetch fails. Iteration occurs when the displayEmotions() function loops through the returned data to display the emotions on the page.
List Creation
restored_reactions = {}
for reaction_data in data:
_ = reaction_data.pop('id', None)
existing_reaction = Emotion.query.filter_by(
user_id=reaction_data.get("user_id"),
title_id=reaction_data.get("title_id")
).first()
Explaination: For each reaction, the code removes the id field using .pop(). This is done because the id is not needed when searching for an existing reaction in the database. Then, it queries the Emotion table using Emotion.query.filter_by() to check if a reaction already exists for the given user_id and title_id. The result is stored in the existing_reaction variable. If a match is found in the database, it will hold that reaction object. Otherwise, it will return None.
List Process
if existing_reaction:
restored_reactions[(reaction_data["user_id"], reaction_data["title_id"])] = existing_reaction.reaction_type
Explaination: If an existing_reaction is found in the database, it adds the reaction to the restored_reactions dictionary. The key of the dictionary is a tuple (user_id, title_id), which uniquely identifies the reaction. The value is the reaction_type (for example: 👍, 🎉, 😂), which is stored in the database.