Function (w/ procedure name, return type, parameters, sequencing, selection, and iteration):
@staticmethod
def restore(data):
for packing_item in data:
packing_id = packing_item.pop('id', None)
if packing_id is not None:
item = Weather.query.get(packing_id)
if item:
item.update(packing_item)
else:
item = Weather(**packing_item)
item.create()
else:
item = Weather(**packing_item)
item.create()
The restore function will restore the items in the database.
- The procedure name is
restoreas you can see by the function name - The return type is a list that represents the items (packing items) being restored from the database
- The parameter (which has an effect on the functionality because it returns different data) are dictionaries which have the packing data.
- The sequence of events: The function iterates over the packing item data. The first if statement checks if the item exists in the database. If it’s found, it will update the database. If it is not found, it will create a new entry for the item.
- For selection, I used the
ifstatement to check if an item already exists in the database. Theifstatement will decide if an entry is updated or a new entry is created. - For iteration, I have a
forloop which iterates through all the items in the database. This allows theifstatements to be performed on each entry in the database and ensure therestorefunction works well.
Call to Function:
def restore_data(data):
with app.app_context():
_ = Weather.restore(data['packing_checklists'])
This code shows that when the restored_data function is called, it restores the data from the packing_checklists table. This restores the data in the database. It takes in the packing data from the database and performs the algorithm as explained earlier.
List Creation:
@token_required()
def get(self):
weather_id = request.args.get('id')
if weather_id:
weather = Weather.query.get(weather_id)
if not weather:
return {'message': 'Weather not found'}, 404
return jsonify(weather)
current_user = g.current_user
is_admin = current_user.role == 'Admin'
all_items = db.session.query(Weather, User).join(User, Weather.user_id == User.id).all()
item_list = [{"id": item.Weather.id, "user_id": item.User._name, "current_user": current_user._name, "is_admin": is_admin, "item": item.Weather.item} for item in all_items]
return jsonify(item_list)
- The variable
item_liststores all the items from the database. - It uses list comprehension which iterates over
all_itemsand creates a list of dictionaries. - Each dictionary has the data from the database
- You can also use a
forloop for this, but list comprehension is more concise and easier to write
Use Data From List:
async function getPackingChecklists() {
try {
const response = await fetch(`${pythonURI}/api/packing_checklists`, {
...fetchOptions,
method: 'GET',
});
if (!response.ok) {
throw new Error('Failed to fetch packing checklists: ' + response.statusText);
}
const data = await response.json();
console.log('Packing checklists get:', data);
const checklistArea = document.getElementById('checklist_area');
checklistArea.innerHTML = '';
let currentUser = data.length > 0 ? data[0].current_user : null;
let isAdmin = data.length > 0 ? data[0].is_admin : false;
console.log("Current user:", currentUser);
console.log("Is admin:", isAdmin);
const filteredData = isAdmin ? data : data.filter(item => item.user_id === currentUser);
const groupedItems = {};
filteredData.forEach(item => {
if (!groupedItems[item.user_id]) {
groupedItems[item.user_id] = {
user_name: item.user_name || `User ${item.user_id}`,
items: []
};
}
groupedItems[item.user_id].items.push(item);
});
Object.values(groupedItems).forEach(userGroup => {
const userSection = document.createElement('div');
userSection.className = 'user-section';
const userHeader = document.createElement('h3');
userHeader.textContent = `User: ${userGroup.user_name.replace(/^User\s+/i, '')}`;
userHeader.className = 'user-section-header';
userSection.appendChild(userHeader);
const userList = document.createElement('ul');
userList.className = 'user-checklist';
userGroup.items.forEach(item => {
const listItem = document.createElement('li');
listItem.className = 'checklist-item';
const nameSpan = document.createElement('span');
nameSpan.textContent = item.item;
const buttonContainer = document.createElement('div');
buttonContainer.className = 'button-container';
const editButton = document.createElement('button');
editButton.className = 'edit-button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
enableEditing(item, listItem, nameSpan, editButton);
});
const removeButton = document.createElement('button');
removeButton.className = 'remove-button';
removeButton.textContent = 'Remove';
removeButton.addEventListener('click', () => {
deletePackingChecklist(item.id);
listItem.remove();
});
buttonContainer.appendChild(editButton);
buttonContainer.appendChild(removeButton);
listItem.appendChild(nameSpan);
listItem.appendChild(buttonContainer);
userList.appendChild(listItem);
});
userSection.appendChild(userList);
checklistArea.appendChild(userSection);
});
} catch (error) {
console.error('Error fetching packing checklists:', error);
alert('Error fetching packing checklists: ' + error.message);
}
};
- In my code, I fetch the data from the backend using a
GETrequest. - After filtering the user based on if they are an admin or not, I iterate through the packing data using list comprehension and display it on the frontend.
- The data I am getting from the backend is a JSONified list that the
GETfunction in the backend is sending whenever it is called. So, when I call the function here, I am using the list and displaying the data for users to see.
Conclusion:
In conclusion, I met all the requirement for my PPR by:
- Defining the
restoreprocedure - Calling the
restoreprocedure through:restore_dataandWeather.restore(data['packing_checklists']) - Storing all the packing items in the
item_list - Using the packing items to display it on the frontend by calling the
GETfunction in the backend which returned a JSONified list from the database.