Adding the Redirect Route

In this step, we will add a new route that takes the short id the application generates and fetch the original URL. Finally, we will redirect users to the original URL.

@app.route('/<short_id>')
def redirect_url(short_id):
    link = ShortUrls.query.filter_by(short_id=short_id).first()
    if link:
        return redirect(link.original_url)
    else:
        flash('Invalid URL')
        return redirect(url_for('index'))
 

This new route accepts a value short_id through the URL and passes it to the url_redirect() view function. For example, visiting http://127.0.0.1:5000/asdf1gHJ would pass the string 'asdf1gHJ' to the short_id parameter.

Inside the view function, we fetch the link from the database using the short_id . If it is not None, the view function will redirect the user to the original_url associated with this short_id using the redirect() Flask helper function, else it will flash an error message to inform the user that the URL is invalid, and redirect them to the index page.

Now we can again run the server and finally test the application.

Discussion

1

0