Deleting a URL
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
First, note that you call the function
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.
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.
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.
main.py 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 must be a part of the URL seen on-screen, and it’s an argument of the
The body of
delete_url() probably looks familiar by now. You use an assignment expression (
:=) to assign
db_url the return of
If a database entry with the provided
secret_key exists and was deactivated, then you return the success message.
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.