URL Building in flask explained and how URL Building takes place in flask

In this tutorial, we are going to learn about the functionalities and features of a URL. We are also going to learn about URL building in Flask and how does the URL building take place in flask.

 

URL Building in Flask

For building URLs in flask, we use the url_for() function. The name of the function is accepted as its first argument and any number of keyword arguments. The unknown variable parts in a website are then appended to the URL as query parameters.

Now a question may have arisen to our mind, that instead of hard-coding the URLs into our templates why are we using the URL reversing function url_for()?

  1. Reversing is often easier than hard-coding the URLs.
  2. You can then change your URLs in one shot instead of manually changing the hard-coded URLs.
  3. URL building also handles the escaping of special characters as well as the Unicode data.
from flask import Flask, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<username>')
def profile(username):
    return '{}'s profile'.format(username)

@app.route('/users/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

The above script has a function profile(username) which accepts a value as an argument from the URL.

The profile() function checks for the argument which is taken from the URL dynamically. It then puts that value passed as an argument in the function. For example – if we run the script and then enter the following URL –

http://localhost:5000/user/CodeSpeedy

Then the following message will show up on the screen –

CodeSpeedy's profile

The above script also has a function named user(name) that accepts a value to its argument from the URL.

The above code checks if an argument received by it matches the word ‘admin’ or not. If it matches, then the application is redirected to the hello_admin() function. And if not, it is passed on to the hello_guest() function.

Run the above code from the python shell.

Goto  − http://localhost:5000/user/admin from your browser

The output will be:

Hello Admin

Enter the following URL in the browser − http://localhost:5000/user/codespeedy

Now the following message gets displayed on the browser −

Hello codespeedy as Guest

 

I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything explained here, please feel free to comment them down below.

Also read:

Leave a Reply