Others


Flask App Routing


App routing in Flask refers to the process of defining URL patterns for your web application and associating those patterns with specific functions that handle the requests. This mechanism determines how your application responds to client requests, mapping URLs to functions that process and return responses.

1.Basic Routing :

To bind a function to an URL path we use the @app.route decorator. In the below example.

app.py
from flask import Flask

app = Flask(__name__)

@app.route('/home')
def home():
    return "Welcome to Home Page"

@app.route('/about')
def about():
    return "Welcome to About Page"

if __name__ == '__main__':
    app.run(debug=True)
  • `/ home` to the `home` function, which returns "Welcome to Home Page".
  • `/about` maps to the `about` function, which returns "Welcome to About Page".

Run the app:

  1. Run 'app.py' file.
  2. Open a web browser and type 'http://127.0.0.1:5000/ or localhost:5000'.

Output:

App Routing

2.Dynamic Routing with Variables:

Dynamic URLs in Flask allow you to create routes that can change based on the input parameters. The dynamic URLs are created using variable rules in the route decorators. These variables can capture parts of the URL and pass them as arguments to the view functions. In the below example.

Flask allows dynamic routing by using variable sections in the URL. This is done by enclosing variables inside < > brackets.

app.py
from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    return f"User: {username}"

if __name__ == '__main__':
    app.run(debug=True)
  • <username> is a dynamic part of the URL. When a URL like `/user/vrsofttech` is accessed, vrsofttech` is captured and passed to the `show_user_profile` function as the username argument.

Output:

Dynamic Routing

3.Specifying Variable Types:

You can specify the type of the dynamic variable to ensure that it matches certain criteria. Common types include `int, `float, `path, by default it is a string.

app.py
@app.route("/user/<int:user_id>")  # Integer only
def show_user(user_id):
    return f"User ID: {user_id}"
  • When a user visits http://127.0.0.1:5000/user/5 will return "User ID:5".
  • When a user trying to visit http://127.0.0.1:5000/user/hello (where "hello" is a string instead of an integer) will result in a 404 Not Found error

Output:

Dynamic Routing

4. Multiple Routes for Single Function

You can use multiple @app.route() decorators for a single function.

app.py
@app.route('/')
@app.route('/home')
@app.route('/index')
def home():
    return "Welcome to the Home Page!"
  • When a user visits http://127.0.0.1:5000/, http://127.0.0.1:5000/home, or http://127.0.0.1:5000/index, all these URLs return "Welcome to the Home Page!" since they are mapped to the same function.

Output:

Dynamic Routing

5. Handling Missing Routes (404 Error)

If a user accesses a non-existing route, Flask raises a 404 error. You can customize this behavior instead of the default error.

app.py
@app.errorhandler(404)
def page_not_found(e):
    return "Oops! Page Not Found.", 404

Output:

Dynamic Routing