Here we are going to see one good practice to create links or URLs in the Flask framework.

Problem:

<a href="/login">Login</a>
<a href="/profile">Profile</a>

The above two links Login and Profile are generated using plain old HTML script, writing links in this way is not really a good idea, if you ever need to organize links in the application then it’s going to be very difficult to find all the links that you have spread out in the application code.

Solution:

Flask provides the solution for this problem in the form of a function called url_for()let’s see how to work with this.

How to create URLs or Links:

We can use the url_for()function to generate the links in the following way.

<a href="{{url_for('login')}}">Login</a>
<a href="{{url_for('profile')}}">Profile</a>

We can pass arguments to the url_for() function, in the above I have passed the name of my view function, the function that handles URL, for this case login and profile

Flask knows the mapping between URLs and functions so it will generate the /loginand /profileURLs for us. This makes the application maintainable because if you want to change the URL, all you need to change the app.route(url)then all the links are going to be automatically updated.

Create Links in routes.py:

In the above example, we have generated the likes on the HTML page, but on the other side of the application, we may also need to generate the likes in backend code that is typically in routes.py.

@app.route('/login', methods=['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.user_name.data == 'admin' and form.password.data == 'admin':
            flash('login successful')
            return redirect('index')
    return render_template('login.html', form=form)

update the above code with url_for()

from app import app
from flask import render_template, flash, redirect, url_for
from app.forms import LoginForm

@app.route('/login', methods=['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.user_name.data == 'admin' and form.password.data == 'admin':
            flash('login successful')
            return redirect(url_for('index'))
    return render_template('login.html', form=form)

Notice that I have changed the redirect URL with the url_for() function. Make sure to import the url_for from the flask package.

Create Links with dynamic values:

The url_for()function accepts several arguments, the very first argument accepts the name of the function and allows any number of keyword arguments.

Example:

user_info = {
        'name':'Chandra'
}
return redirect(url_for('index'), user=user_info)

References:

Happy Learning 🙂