Full Stack Documentation
Model Class: Sports
Columns:
-
id: An integer primary key (automatically generated by the database).
-
_sport: A string representing the sport name.
-
_emoji: A string representing the emoji associated with the sport.
class Sports(db.Model):
__tablename__ = 'sports'
id = db.Column(db.Integer, primary_key=True)
_sport= db.Column(db.String(255), nullable=False)
_emoji = db.Column(db.String(255), nullable=False)
Methods:
-
create(): Saves the current Sports object to the database. It commits the transaction, but rolls back if an exception occurs.
-
read(): Returns a dictionary containing the object’s data (id, sport, and emoji). This method helps convert the object into a format suitable for sending as JSON to the frontend.
-
update(self, inputs): Updates the object’s attributes based on the provided inputs dictionary. It then attempts to commit the changes to the database. If there’s a unique constraint violation (IntegrityError), it rolls back the transaction.
-
@staticmethod restore(data): This static method takes a list of dictionaries (data) and tries to restore them as Sports objects in the database. It iterates through the data, checks for existing entries based on the emoji (assuming it’s unique), and updates them if found. Otherwise, it creates new entries.
def read(self):
"""
The read method retrieves the object data from the object's attributes and returns it as a dictionary.
Returns:
dict: A dictionary containing the group data.
"""
return {
'id': self.id,
'sport': self._sport,
'emoji': self._emoji,
}
SportAPI Class:
- AddSport.post(): This method handles POST requests to the /api/sports/add endpoint.
- SportAPI.get(): This method handles GET requests to the /api/sports endpoint.
- SportAPI.put(): This method handles PUT requests to the /api/sports endpoint, intended for updating sports data.
- SportAPI.delete(): This method handles DELETE requests to the /api/sports endpoint, intended for deleting sports data.
API’s role in full stack devolpment
- This code separates the data access logic (using the Sports model class) from the API layer (implemented using Flask-RESTful). This promotes better code organization and maintainability.
- The API provides well-defined endpoints for CRUD operations, making it easy for frontend applications to interact with sports data. The frontend can send requests (GET, POST, PUT, DELETE) to these endpoints along with any necessary data (e.g., sport name, emoji) in the request body.
- The API uses JSON for data exchange, which is a widely used format for APIs and simplifies data transfer between the frontend and backend.
The HTML code in the frontend
- The code helps build a visual table with columns of ID, Sport, Emoji, Update, and Delete.
- It also created a create sport button which is assigned function later in the code
The JavaScript code in the Frontend
- The createSport function:
- Prompts the user to enter a sport name and emoji.
- If both are provided, it sends a POST request to the /api/sports/add endpoint with the sport and emoji data in JSON format.
- Upon successful response (containing the newly created sport data), it calls the displaySport function to add the new sport to the table.
- The updateMenu function:
- Prompts the user to enter a new emoji for updating.
- Sends a PUT request to the /api/sports/add endpoint with the new emoji data in JSON. Updates the emoji cell directly in the table row for the corresponding sport.
- The deleteSport function:
- Sends a DELETE request to the /api/sports/ endpoint with the sport ID in JSON.
- Removes the corresponding sport row from the table.
- The displaySport function:
- Takes a sport data object as input.
- Creates a new table row and populates it with the sport’s ID, sport name, emoji, update button, and delete button.
- Appends the new row to the table body.
function createSport() {
const sport = prompt("Enter Extracirrcular:");
const emoji = prompt("Enter Corrsponding emoji:");
if (!sport || !emoji) return;
fetch(`${pythonURI}/api/sports/add`, {
...fetchOptions,
method: "POST",
body: JSON.stringify({ sport, emoji }),
})
.then((res) => res.json())
.then((newSport) => {
displaySport(newSport);
});
}
// Update the pick of a class
async function updateMenu(id) {
let newEmoji = prompt("Enter new Emoji:");
if (!newEmoji) return;
await fetch(`${pythonURI}/api/sports/add`, {
...fetchOptions,
method: "PUT",
body: JSON.stringify({ emoji: newEmoji, id }),
});
// Update the pick in the table directly
const row = document.querySelector(`[data-id="${id}"]`);
row.querySelector('.emoji').textContent = newEmoji;
}
// Delete a class from the table
async function deleteSport(id) {
if (!confirm("Are you sure you want to delete this sport?")) return;
await fetch(`${pythonURI}/api/sports/add`, { // Ensure correct endpoint
...fetchOptions,
method: "DELETE",
body: JSON.stringify({ id }),
});
// Remove the row from the table
const row = document.querySelector(`[data-id="${id}"]`);
if (row) row.remove();
}
fetch(`${pythonURI}/api/sports/add`, {
...fetchOptions,
method: "GET"
})
.then((res) => res.json())
.then((sports) => {
sports.forEach(displaySport);
});
Frontend’s role in Full Stack Development
- The frontend code interacts with a Flask-RESTful API on the backend using Fetch API for data exchange.
- The frontend handles user interactions (adding new sports, updating emojis, deleting sports) and triggers appropriate API requests to the backend for data manipulation.
- The code uses DOM manipulation (adding/removing table rows) to update the user interface based on the data received from the backend.