How To Redirect To Url In Python Flask

How To Redirect To Url In Python Flask

The redirect() function allows us to redirect a user to the URL of our choice. In the Flask application that we are building so far, we have a /shortenurl route that checks to see what method type is in use. If it is a GET request, we are simply returning some text to the user. Instead of that, we can redirect them to the homepage so they can enter a URL and shortcode. The use of redirect is highlighted in the code here.

flask-tutorial\app.py

from flask import Flask, render_template, request, redirect

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
    if request.method == 'POST':
        return render_template('shortenurl.html', shortcode=request.form['shortcode'])
    elif request.method == 'GET':
        return redirect('/')
    else:
        return 'Not a valid request method for this route'

Now try going to 127.0.0.1:5000/shortenurl directly in the web browser. You will find that you are instantly redirected to the home (/) route and the form we created earlier is displayed.

python flask redirect to url


url_for()

Another method you can use when performing redirects in Flask is the url_for() function. The way that url_for() works is instead of redirecting based on the string representation of a route, you provide the function name of the route you want to redirect to. So if we update the code to the snippet here, we get the same result but using url_for() instead of redirect(). Also note that both redirect, and url_for are imported on the first line of app.py.

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
    if request.method == 'POST':
        return render_template('shortenurl.html', shortcode=request.form['shortcode'])
    elif request.method == 'GET':
        return redirect(url_for('home'))
    else:
        return 'Not a valid request method for this route'

Shortcode To URL Redirects

This app takes two inputs, a URL you would like to visit and the short code that represents that URL. So for example, if you type yhoo, you would like to be sent to https://yahoo.com. To get started with this, let’s set up a JSON file to store the short code / URL combinations that the app receives as input. The following highlighted code stores each shortcode / URL combination and makes sure to check there are no duplicates to ensure that each shortcode is unique for only one given URL.

from flask import Flask, render_template, request, redirect, url_for
import json
import os.path

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
    if request.method == 'POST':
        urls = {}
        if os.path.exists('urls.json'):
            with open('urls.json') as url_storage:
                urls = json.load(url_storage)
        if request.form['shortcode'] in urls.keys():
            return redirect(url_for('home'))
        urls[request.form['shortcode']] = request.form['url']
        with open('urls.json', 'w') as url_storage:
            json.dump(urls, url_storage)
        return render_template('shortenurl.html', shortcode=request.form['shortcode'])
    elif request.method == 'GET':
        return redirect(url_for('home'))
    else:
        return 'Not a valid request method for this route'

Now when we add another shortcode / URL combination, it shows up in the JSON storage that was created.

flask form input before redirect

flask store url in json

In the Flask project root, there is now a urls.json file and when we open it, the data we have submitted so far is there.
flask json storage


Performing Redirect Of Shortcode To URL

At this point, we can add the code that will take a user from the shortcode to an actual website. So for example, using the data we have already stored in the JSON file, we would like to be able to visit http://127.0.0.1:5000/yhoo and the result will be loading https://yahoo.com. Likewise, http://127.0.0.1:5000/twtr should load https://twitter.com. The way to do this is with a variable route that uses the shortcode itself as the route. In the following shortcode_redirect() function, we capture the shortcode that is typed into the browser. In other words, visiting http://127.0.0.1:5000/yhoo means ‘yhoo’ is the shortcode. Then, we check for the existence of that shortcode in the JSON storage that has been set up. If it exists, then we redirect the user to the full URL that is associated with that given shortcode.

from flask import Flask, render_template, request, redirect, url_for
import json
import os.path

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
    if request.method == 'POST':
        urls = {}
        if os.path.exists('urls.json'):
            with open('urls.json') as url_storage:
                urls = json.load(url_storage)
        if request.form['shortcode'] in urls.keys():
            return redirect(url_for('home'))
        urls[request.form['shortcode']] = request.form['url']
        with open('urls.json', 'w') as url_storage:
            json.dump(urls, url_storage)
        return render_template('shortenurl.html', shortcode=request.form['shortcode'])
    elif request.method == 'GET':
        return redirect(url_for('home'))
    else:
        return 'Not a valid request method for this route'


@app.route('/<string:shortcode>')
def shortcode_redirect(shortcode):
    if os.path.exists('urls.json'):
        with open('urls.json') as url_storage:
            urls = json.load(url_storage)
            if shortcode in urls.keys():
                return redirect(urls[shortcode])

Sure enough, this is working now.

Learn More About How To Redirect In Flask