Implementing Key Programming Concepts in Flask with SQLite
1. Student-Developed Procedure Implementation
Procedure Definition
The following function is a student-developed procedure that defines a method to manage sections in an SQLite database. This function includes sequencing (logical steps), selection (conditional checks), and iteration (looping through data):
@sections_bp.route('/sections', methods=['GET', 'POST'])
def manage_sections():
if request.method == 'GET':
try:
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
cursor = conn.cursor()
cursor.execute("SELECT * FROM sections")
sections = [{"id": row[0], "name": row[1], "theme": row[2]} for row in cursor.fetchall()]
return jsonify(sections), 200
except Exception as e:
return jsonify({"error": f"Failed to fetch sections: {e}"}), 500
finally:
if 'conn' in locals():
conn.close()
Procedure Call
Here is where the above procedure is being called in the program when handling a GET request to retrieve sections:
app.register_blueprint(sections_bp)
2. List Usage for Managing Complexity
Storing Data in a List
A list is used to store predefined sections and their themes before inserting them into the SQLite database:
static_data = [
("Fiction", "Mystery"),
("Non-Fiction", "Educational"),
("Science Fiction", "Futuristic"),
("Fantasy", "Adventure"),
("Biography", "Inspiration")
]
for name, theme in static_data:
try:
cursor.execute("INSERT INTO sections (_name, _theme) VALUES (?, ?)", (name, theme))
except sqlite3.IntegrityError:
pass
Using Data from the List
This segment demonstrates how the data in the list is used to create new data and access multiple elements in the list when fetching and displaying section data:
cursor.execute("SELECT * FROM sections")
sections = [{"id": row[0], "name": row[1], "theme": row[2]} for row in cursor.fetchall()]
This process enables the retrieval and structured use of stored data, ensuring the program effectively fulfills its purpose.