In this final lesson, we will cover how to enable the delete button so that you can delete a booking from your system. If you have followed along with the previous video, you should now have a functional form for updating individual records in your database. We will now implement the delete functionality, allowing users to remove bookings from the system.
First, navigate to the code where we have set up our last endpoint, named delete
. In the delete endpoint, we will start by fetching the database and getting a cursor object. The cursor object is necessary for querying the database.
def delete(reference_number):
# Get the database and create a cursor
db = get_db()
cursor = db.cursor(dictionary=True)
Before deleting a booking, we need to ensure that the booking exists in the database. To do this, we will use a SELECT
statement with a small trick. Instead of selecting the booking record, we will select the number 1
if the booking exists in the database.
# Check if the booking exists
cursor.execute("SELECT 1 FROM booking WHERE reference_number = %s", (reference_number,))
booking = cursor.fetchone()
If the result of the query is None
, it means that the booking does not exist in the database. We can abort the delete process in this case:
# Abort if booking is not found
if booking is None:
cursor.close()
abort(404)
Once we have confirmed that the booking exists in the database, we can proceed to delete it. To do this, we will use a DELETE
statement:
# Delete the booking
cursor.execute("DELETE FROM booking WHERE reference_number = %s", (reference_number,))
We also need to commit the changes to the database and close the cursor:
db.commit()
cursor.close()
Now, let's test the delete functionality. Navigate to the booking list and select a booking. Click the delete button and observe that the booking has been removed from the list.
In this final lesson, we have demonstrated how to enable the delete button in a Flask web app, allowing users to remove bookings from the system. The essential steps include setting up the delete endpoint, verifying if the booking exists in the database, and then performing the actual deletion.
The code should now be able to:
- View the list of all the records in the database.
- Get information from different tables, e.g., guest name and room type.
- Create new reservations in the system.
- Update reservations.
- Delete reservations.
With these capabilities, your web app should now be fully functional for managing bookings!