Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Deleting a URL

00:00 Delete a URL. Your Python URL shortener app is great for sharing a link with friends. Once they’ve visited a link, you may want to delete the shortened URL. Just as with the update_db_clicks() function, you start by creating a new function in

00:27 First, note that you call the function deactivate_db_url_by_secret_key() and delete_db_url_by_secret_key(). Consequently, you set the .is_active attribute to False instead of deleting the database entry completely. Remember that the database queries where you requested a URL object contained the filter that the URL must be active.

00:52 This means that any deactivated URLs won’t get returned in the database calls. To the user, it will look like the URL was deleted, but only you as a super admin can actually complete the deletion action.

01:05 This has the advantage that you can recover a deactivated URL if a user changes their mind about it being disabled. This function takes secret_key as an argument.

01:16 Only the creator of a shortened URL knows this secret_key. It’s a good security measure when only the creator can deactivate a URL. Now, the only part that’s missing is an endpoint to call this function.

01:31 Open one last time and add a delete_url() function, as seen on-screen. You use the @app.delete() decorator to indicate that delete_url() accepts DELETE requests. However, this deletion action is only allowed if the request body contains the appropriate secret_key.

01:52 This secret_key must be a part of the URL seen on-screen, and it’s an argument of the delete_url() function.

02:06 The body of delete_url() probably looks familiar by now. You use an assignment expression (:=) to assign db_url the return of crud.deactivate_db_url_by_secret_key().

02:21 If a database entry with the provided secret_key exists and was deactivated, then you return the success message.

02:36 Otherwise you trigger raise_not_found(). Now you’re able to deactivate URLs that aren’t needed anymore. When a shortened URL is active, it will forward you to the target URL.

02:53 But once you deactivate it,

03:08 the forward to the target URL won’t work anymore. This means you’ve created a fully functional URL shortener. In the next section of the course, you’ll review what you’ve covered.

Become a Member to join the conversation.