![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
Final Blog for Sprint 5
Explanation of Sprint 5 all together
- Groups Purpose
- My purpose
- 2. Input/Output Demonstrations/List Requests
- 3. Backend Features
- CRUD
- Creating a Care Center
- Reading the Care Center
- Updating the Care Center
- Deleting the Care Center
- 4. Call to Algorithm request(Algorithms)
- 5. Challenges and Improvements
- 6. Addressing Learning Requirements
- 7. Third-Party Libraries
Groups Purpose
- Our goal is to create a budget-friendly travel planner that helps travelers find important resources, such as activities, hotels, restaurants, and healthcare facilities while they are away from home.
My purpose
- My purpose is about Wellness Waypoints, a program designed to help people find the nearest care centers (like hospitals or pharmacies) based on their injury and city.
Why This Program?
The program solves a simple problem: If you’re injured, where can you go for help? It finds the best places near you and shows them on a map.
What Did I Work On?
- I created the tools (backend) that store information about care centers.
- I built features (frontend) that let users search for care centers and see them on a map.
- I set up the database so it can be saved, backed up, and restored.
2. Input/Output Demonstrations/List Requests
What Happens on the Website?
Users can:
- Select an injury from a dropdown.
- Type in the name of their city.
- Click “Go” to see a list of care centers and their locations on a map.
Code Example:
async function FindLocations() {
const location = document
.getElementById("location")
.value.trim()
.replace(/\s+/g, "+");
const place = document
.getElementById("place")
.value.trim()
.replace(/\s+/g, "+");
if (!place) {
alert("Please enter a valid city.");
return;
}
const url = `https://nominatim.openstreetmap.org/search?q=${location}+in+${place}&format=json&addressdetails=1&limit=10`;
```
```
function checkinCareLocation(title) {
const location = document
.getElementById("location")
.value.trim();
const place = document
.getElementById("place")
.value.trim();
const injury = document
.getElementById("injury")
.value.trim();
postCareCenterData(injury, location, title);
alert(`Checked in for:${injury} to ${location} \nlocated in city:${place} \nat address:${title}`);
console.log(`Checked in for:${injury} to ${location} \nlocated in city:${place} \nat address:${title}`);
getCareCenterData(currentUserID);
}
if (data.length === 0) {
const noResultsRow = document.createElement("tr");
noResultsRow.innerHTML = `<td colspan="6">No care center check-ins available.</td>`;
carecenterTable.appendChild(noResultsRow);
return;
}
const row = document.createElement("tr");
row.innerHTML = `
<td>${index + 1}</td>
<td>${waypoint.injury}</td>
<td>${waypoint.location}</td>
<td>${waypoint.address}</td>
<td>
<div class="ratings">
${[1, 2, 3, 4, 5]
.map((rating) => `
<span
class="rating-star
${rating <= waypoint.rating ?
(rating <= 2 ? "red" : rating <= 4 ? "yellow" : "green") : ""}
${rating <= waypoint.rating ? "active" : ""}"
data-rating="${rating}"
data-waypointid="${waypoint.id}">
★
</span>
`)
.join("")}
</div>
</td>
<td>
<button class="checkout-button" data-waypointid="${waypoint.id}">
Check Out
</button>
</td>
`;
- What This Does: This code takes the user’s input, asks a website (API) for care center locations, and shows the results in a table.
Using Postman
Postman is a tool we use to test APIs. Here’s an example:
- Request to Add a Care Center:
{ "injury": "Fracture", "location": "Hospital A", "address": "123 Main St" }
- Response:
{ "id": 1, "injury": "Fracture", "location": "Hospital A", "address": "123 Main St" }
3. Backend Features
Creating a Care Center
This code adds a new care center to the database:
@token_required
def post(self):
data = request.get_json()
if not all(key in data for key in ["injury", "location", "address"]):
return {"message": "Missing required fields"}, 400
center = CareCenter(**data)
center.create()
return jsonify(center.read()), 201
- What This Does: It checks if all fields (injury, location, address) are provided and then saves the care center to the database.
Database Queries
We use Python to ask the database for information. For example:
centers = CareCenter.query.filter_by(location="Hospital A").all()
return jsonify([center.read() for center in centers])
- What This Does: It looks for care centers in “Hospital A” and sends the results back as a list.
Algorithmic code request
CRUD
POST: - Used to create a new resource on the server. For example, submitting a form to add a new user.
GET: - Retrieves data from the server without altering its state. For instance, fetching user details.
PUT: - Replaces an existing resource with new data. If the resource doesn’t exist, it can create it. For example, updating a user’s profile information.
DELETE - Removes a specified resource from the server, such as deleting a user account.
Creating a Care Center
This code adds a new care center to the database:
class _CRUD(Resource):
@token_required()
def post(self):
"""
Create a new waypointuser.
"""
# Obtain the current user from the token required setting in the global context
current_user = g.current_user
# Obtain the request data sent by the RESTful client API
data = request.get_json()
# Validate the presence of required keys
if not data:
return {'message': 'No input data provided'}, 400
if 'injury' not in data:
return {'message': 'Waypoint title is required'}, 400
if 'location' not in data:
return {'message': 'Waypoint comment is required'}, 400
if 'address' not in data:
data['address'] = {}
if 'rating' not in data:
data['rating'] = 5
current_user = g.current_user
# Create a new waypoint object using the data from the request
waypointsuser = WaypointsUser(data['injury'], data['location'], data['address'], data['rating'], current_user.id)
# Save the waypoint object using the Object Relational Mapper (ORM) method defined in the model
waypointsuser.create()
# Return response to the client in JSON format, converting Python dictionaries to JSON format
return jsonify(waypointsuser.read())
-
What This Does: It checks if all fields (injury, location, address) are provided and then saves the care center to the database.
Reading the Care Center
Users can fetch all the waypoints that belong to them.
@token_required() def get(self): """ Retrieve a single waypoint by ID. """ # Obtain and validate the request data sent by the RESTful client API current_user = g.current_user waypointsuser = WaypointsUser.query.filter_by(_user_id=current_user.id) if waypointsuser is None: return {'message': 'Waypoint not found'}, 404 # Convert Python object to JSON format waypointsusers = waypointsuser.all() json_waypointsuser = [waypointsuser.to_dict() for waypointsuser in waypointsusers] return jsonify(json_waypointsuser) # Return a JSON restful response to the client return jsonify(json_ready)
-
What This Does: It fetches and returns all waypoints stored for a specific user.
Updating the Care Center
Allows users to update waypoint details.
@token_required() def put(self): """ Update a waypoint. """ # Obtain the current user current_user = g.current_user # Obtain the request data data = request.get_json() # Find the current waypoint from the database table(s) waypointsuser = WaypointsUser.query.get(data['waypoint_id']) if waypointsuser is None: return {'message': 'WaypointUser not found'}, 404 # Update the waypoint waypointsuser._rating = data['rating'] # Save the waypoint waypointsuser.update() # Return response return jsonify(waypointsuser.read())
-
What This Does: Finds a waypoint, updates its details, and saves the changes.
Deleting the Care Center
This function allows users to remove a waypoint they no longer need.
@token_required()
def delete(self):
"""
Delete a waypoint.
"""
waypoint_id = request.args.get('waypoint_id')
# Find the current waypoint from the database table(s)
waypointsuser = WaypointsUser.query.filter_by(id=waypoint_id).first()
if waypointsuser is None:
return {'message': 'Waypoint not found'}, 404
# Delete the waypoint using the ORM method defined in the model
waypointsuser.delete()
# Return response
return jsonify({"message": "Waypoint deleted"})
- What This Does: It looks for a specific waypoint by ID and deletes it.
4. Call to Algorithm request(Algorithms)
Handling User Requests
This function sends user data (like an injury) to the server and saves it:
async function postCareCenterData(injury, location, address) {
const postData = { injury, location, address };
try {
const response = await fetch(`${pythonURI}/api/waypoints`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(postData),
});
if (!response.ok) throw new Error("Failed to post data");
const result = await response.json();
console.log("Successfully posted:", result);
} catch (error) {
console.error("Error posting data:", error);
}
}
- What This Does: Sends data to the backend and saves it. If there’s an error, it shows a message.
5. Challenges and Improvements
Challenges
- Making the map update automatically.
- Handling errors when the API doesn’t work as expected.
- Debugging API responses to figure out what went wrong.
Improvements
- Added better error messages for missing fields.
- Made the database queries faster.
- Improved how markers appear on the map.
6. Addressing Learning Requirements
- Teamwork: Built features that connect the frontend and backend.
- Algorithms: Used Python and JavaScript to manage user inputs, save data, and display results.
- API Testing: Used tools like Postman to check how the backend handles requests.
- Database Management: Created, backed up, and restored data using SQLAlchemy.
7. Third-Party Libraries
- SQLAlchemy: Makes working with databases easier.
- Leaflet.js: Displays care center locations on a map.
- OpenStreetMap API: Provides location data based on user input.
Conclusion
The Wellness Waypoints project shows how coding can solve real-life problems. It connects users with care centers quickly and efficiently, making the program both useful and practical.