![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
PPR Blog
My PPR Blog
- Issue: Implementing Key Programming Concepts in Flask with SQLite
- 1. Student-Developed Procedure Implementation
- 2. List Usage for Managing Complexity
Issue: Implementing Key Programming Concepts in Flask with SQLite
Description
- This issue focuses on implementing key programming concepts using Flask and SQLite, incorporating student-developed procedures and list usage for managing complexity.
1. Student-Developed Procedure Implementation
Procedure Definition
- The following function is a student-developed procedure that defines a method to manage waypoints in an SQLite database. This function includes sequencing (logical steps), selection (conditional checks), and iteration (looping through data):
Text Reference:
- “The function defines a method to manage sections, including logical steps for data retrieval, handling errors, and database i- teraction.”
class _GETWaypoints(Resource):
@token_required()
def get(self):
"""
Retrieve a single waypoint by ID or all waypoints if no ID is provided.
"""
data = request.get_json()
if data is None or 'id' not in data:
waypoints = Waypoints.query.all()
json_waypoints = [waypoint.to_dict() for waypoint in waypoints]
return jsonify(json_waypoints)
waypoints = Waypoints.query.get(data['id'])
if waypoints is None:
return {'message': 'Waypoint not found'}, 404
json_ready = waypoints.read()
return jsonify(json_ready)
Procedure Call
- Here is where the above procedure is being called in the program when handling a GET request to retrieve waypoints:
api.add_resource(WaypointAPI._GETWaypoints, '/waypoints')
2. List Usage for Managing Complexity
Storing Data in a List
- A list is used to store predefined waypoints and their details before inserting them into the SQLite database:
static_data = [
{"injury": "Sprained Ankle", "location": "Trailhead A", "address": "123 Mountain Rd", "rating": 4},
{"injury": "Heat Exhaustion", "location": "Desert Loop", "address": "456 Sand Dune Dr", "rating": 3},
{"injury": "Dehydration", "location": "Canyon Base", "address": "789 Riverbank St", "rating": 5}
]
for entry in static_data:
try:
waypointsuser = WaypointsUser(
entry['injury'], entry['location'], entry['address'], entry['rating'], 1
)
waypointsuser.create()
except Exception as e:
print(f"Error inserting waypoint: {e}")
Using Data from the List
- This segment demonstrates how the data in the list is used to retrieve waypoints and access multiple elements when fetching and displaying waypoint data:
waypoints = Waypoints.query.all()
json_waypoints = [{"id": w.id, "injury": w._injury, "location": w._location, "rating": w._rating} for w in waypoints]