Python Flask App Routing

We offer you a brighter future with placement-ready courses - Start Now!!

Flask is a popular web framework for building web applications in Python. One of the key features of Flask is its built-in routing functionality, which allows developers to define how different URLs should be handled by their application. In this article, we will take a deep dive into Flask app routing, exploring its various features and how to use them effectively in your web applications.

What is Routing in Flask?

Routing is the process of mapping URLs to specific functions or views in a web application. In Flask, routing is achieved through the use of decorators, which are special annotations that can be applied to Python functions. These decorators define how different URLs should be handled by Flask, and what functions or views should be executed when those URLs are accessed.

To get started with routing in Flask, you first need to create a Flask application. Here’s a simple example of how you can create a basic Flask app:

from flask import Flask


app = Flask(__name__)


@app.route('/')
def hello():
   return "Hello, Pythongeeks!"


if __name__ == '__main__':
   app.run(debug=True)

In the code above, we first import the Flask module and create a Flask application using the Flask class. We then define a route for the root URL (“/”) using the @app.route() decorator, followed by the function that should be executed when that URL is accessed. In this case, the function is called hello() and it returns the string “Hello, Pythongeeks!”.

You can run this Flask app using the app.run() method, which starts the Flask development server. Once the server is running, you can access the root URL in your web browser (e.g., http://localhost:5000/) and you should see the “Hello, World!” message displayed.

Flask Route Decorators

Flask provides several decorators for defining routes in your web application. Let’s take a look at some of the commonly used ones:

1. @app.route(‘/’):

This decorator is used to define the handler for the root URL (“/”). When a user accesses the root URL of your web application, Flask will execute the function that is decorated with @app.route(‘/’).

@app.route('/')
def home():
   return "Welcome to the pythongeeks page!"

2. @app.route(‘/about’):

This decorator is used to define the handler for a specific URL (“/about” in this case). When a user accesses the “/about” URL of your web application, Flask will execute the function that is decorated with @app.route(‘/about’).

@app.route('/about')
def about():
   return "This is the pythongeeks about page!"

3. @app.route(‘/<string: name>’):

This decorator is used to define a URL with a variable part (in this case, a string variable called name). The value of the variable part in the URL will be passed as an argument to the function that is decorated with @app.route(‘/<string: name>’).

@app.route('/user/<string:name>')
def user(name):
   return f"Hello, pythongeeks {name}!"

4. @app.route(‘/<int:id>’):

This decorator is used to define a URL with a variable part that should be an integer (in this case, an integer variable called id). The value of the variable part in the URL will be converted to an integer and passed as an argument to the function that is decorated with @app.route(‘/<int:id>’).

@app.route('/post/<int:id>')
def post(id):
   return f"Showing post with pythongeeks ID {id}!"

5. @app.route(‘/<float:price>’):

This decorator is used to define a URL with a variable part that should be a floating-point number (in this case, a float variable called price). The value of the variable part in the URL will be converted to a float and passed as an argument to the function that is decorated with @app.route(‘/<float:price>’).

@app.route('/product/<float:price>')
def product(price):
   return f"Pythongeeks Product price: ${price:.2f}"

6. @app.route(‘/<path:path>’):

This decorator is used to define a URL with a variable part that can contain slashes (in this case, a path variable called path). The value of the variable part in the URL will be passed as a string argument to the function that is decorated with @app.route(‘/<path:path>’).

@app.route('/page/<path:path>')
def page(path):
   return f"Accessing pythongeeks page: {path}"

These are just a few examples of the route decorators available in Flask. You can also use other decorators such as @app.route(‘/<uuid:uuid>’) for handling UUIDs or @app.route(‘/<regex(regex):value>’) for handling URLs with custom regular expressions.

HTTP Methods

In addition to specifying the URL pattern, Flask route decorators also allow you to specify the HTTP methods that should be allowed for a particular URL. By default, Flask routes are associated with the GET method, which is used for retrieving information. However, you can also specify other HTTP methods such as POST, PUT, DELETE, and more, to handle different types of requests.

Here’s an example of how you can specify different HTTP methods for a route in Flask:

@app.route('/api/users', methods=['GET', 'POST'])
def users():
   if request.method == 'GET':
       # Logic for handling GET request
       return "Get users"
   elif request.method == 'POST':
       # Logic for handling POST request
       return "Create user"

In the code above, we have defined a route for “/api/users” that allows both GET and POST methods. Inside the function, we can use the request.method attribute to determine the HTTP method used in the request, and then execute the appropriate logic accordingly.

Route Variables in Flask

As we have seen in the previous examples, Flask allows you to define routes with variable parts in the URL. These variable parts act as placeholders and can capture different types of values from the URL, such as strings, integers, floats, and paths. These captured values can then be passed as arguments to the function that handles the route.

Let’s take a closer look at how you can work with route variables in Flask

@app.route('/user/<string:name>')
def user(name):
   return f"Hello, pythongeeks {name}!"


@app.route('/post/<int:id>')
def post(id):
   return f"Showing post with pythongeeks ID {id}!"


@app.route('/product/<float:price>')
def product(price):
   return f"Product pythongeeks price: ${price:.2f}"


@app.route('/page/<path:path>')
def page(path):
   return f"Accessing pythongeeks page: {path}"

In the code above, we have defined routes with different variable parts, such as <string:name>, <int:id>, <float:price>, and <path:path>. These variable parts are enclosed in angle brackets < > and are used to capture values from the corresponding parts of the URL. For example, in the /user/<string:name> route, the value after the /user/ ‘

part of the URL will be captured as a string and passed as the name argument to the user() function.

You can use these captured values in your function to perform logic or generate dynamic responses based on the values from the URL. For example, in the user() function above, the captured name value from the URL is used to generate a personalized greeting.

Flask URL Building

Flask also provides a built-in feature for generating URLs dynamically based on the defined routes. This is useful when you want to generate URLs with variable parts or when you want to create links to other pages within your Flask application.

You can use the url_for() function in Flask to generate URLs based on the names of the functions that handle the routes. The url_for() function takes the name of the function as an argument and returns the URL that corresponds to that function.

Here’s an example of how you can use the url_for() function in your Flask application:

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def home():
   return "Welcome to the pythongeeks page!"

@app.route('/user/<string:name>')
def user(name):
   return f"Hello, {name}!"

@app.route('/post/<int:id>')
def post(id):
   return f"Showing post with ID {id}!"

@app.route('/product/<float:price>')
def product(price):
   return f"Product price: ${price:.2f}"


@app.route('/page/<path:path>')
def page(path):
   return f"Accessing page: {path}"


if __name__ == '__main__':
   with app.test_request_context():
       print(url_for('home')) # Output: /
       print(url_for('user', name='John')) # Output: /user/John
       print(url_for('post', id=1)) # Output: /post/1
       print(url_for('product', price=9.99)) # Output: /product/9.99
       print(url_for('page', path='about')) # Output: /page/about

In the code above, we have defined routes for different URLs using the route decorators as we discussed earlier. Inside the if __name__ == ‘__main__’: block, we use the url_for() function to generate URLs for different functions. The first argument to url_for() is the name of the function that handles the route, and we can pass additional keyword arguments to specify the values for the variable parts in the URL.

Flask Redirect()

In some cases, you may want to redirect users to a different URL or route within your Flask application. Flask provides the redirect() function that allows you to redirect users to a different URL.

Here’s an example of how you can use the redirect() function in Flask:

from flask import Flask, redirect


app = Flask(__name__)


@app.route('/')
def home():
   return "Welcome to the pythongeeks page!"


@app.route('/login')
def login():
   # Logic for handling login
   return redirect(url_for('user', name='John'))


@app.route('/user/<string:name>')
def user(name):
   return f"Hello, {name}!"


if __name__ == '__main__':
   app.run(debug=True)

In the code above, we have defined a /login route that handles the logic for user login. After successful login, we use the redirect() function to redirect the user to the /user route with the name parameter set to “John”. The url_for() function is used to generate the URL for the user() function based on its name.

Error Handling in Flask

Error handling is an important aspect of any web application. Flask provides built-in error handling mechanisms that allow you to handle different types of errors, such as 404 (not found) errors, 500 (internal server errors), and others. You can define error handlers in your Flask application to handle these errors and provide custom error pages or responses to users.

To define an error handler in Flask, you can use the errorhandler decorator provided by the Flask module. You can specify the type of error you want to handle as an argument to the decorator. Here’s an example:

from flask import Flask


app = Flask(__name__)


@app.errorhandler(404)
def not_found(error):
   return "Page not found", 404


@app.errorhandler(500)
def internal_server_error(error):
   return "Internal server error", 500


if __name__ == '__main__':
   app.run(debug=True)

In the code above, we have defined error handlers for 404 and 500 errors. The not_found() function is called when a 404 error occurs, and it returns the response “Page not found” with a 404 status code. Similarly, the internal_server_error() function is called when a 500 error occurs, and it returns the response “Internal server error” with a 500 status code.

You can define error handlers for other types of errors as well, such as 403 (forbidden), 401 (unauthorized), and so on, by using the appropriate status codes in the errorhandler decorator.

Middleware in Flask

Middleware in Flask is a way to intercept requests and responses before they are processed by the route functions or after they are generated by the route functions. These can be used to perform actions such as authentication, authorization, logging, caching, and others.

Flask allows you to define middleware functions using the before_request and after_request decorators. The before_request decorator is used to define middleware

functions that are executed before the route functions, and the after_request decorator is used to define middleware functions that are executed after the route functions.

Here’s an example of how you can define middleware functions in Flask:

from flask import Flask, request


app = Flask(__name__)


@app.before_request
def before_request():
   # Logic to be executed before the route functions
   pass


@app.after_request
def after_request(response):
   # Logic to be executed after the route functions
   return response


@app.route('/')
def home():
   return "Welcome to the pythongeeks home page!"


if __name__ == '__main__':
   app.run(debug=True)

In the code above, we have defined a before_request middleware function and an after_request middleware function. The before_request() function is executed before any route function is called, and the after_request() function is executed after the route function returns a response. You can define your own logic inside these middleware functions, such as checking for authentication, logging, modifying the request or response, and others

Conclusion

In this article, we have discussed Flask app routing, including defining routes, capturing URL parameters, generating URLs, handling errors, and implementing middleware. With this knowledge, you can now start building sophisticated web applications using Flask with proper routing and URL handling. Happy Flask coding!

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


PythonGeeks Team

PythonGeeks Team is dedicated to creating beginner-friendly and advanced tutorials on Python programming, AI, ML, Data Science and more. From web development to machine learning, we help learners build strong foundations and excel in their Python journey.

Leave a Reply

Your email address will not be published. Required fields are marked *