About add_url_rule in Flask 3.0
Hello! Today, we want to discuss one of the extraordinary features of the Flask framework. The add_url_rule
function allows you to add a new URL pattern to a blueprint. This action makes it possible to easily manage routes and keep your own code organized.
Blueprints in Flask help you divide large applications into smaller sections. For instance, if you have a large website, you can separate different sections like user management and website content into distinct blueprints. This process can make organizing your codes much easier.
The add_url_rule
method can be used as follows. You specify the URL and the function that should be executed for that URL. You can also specify different HTTP methods like GET and POST for the same route.
Let's take a simple example. This example includes a blueprint where we add two URLs using add_url_rule
. This action helps remember how to manage routes.
from flask import Flask, Blueprint
app = Flask(__name__)
my_blueprint = Blueprint('my_blueprint', __name__)
@my_blueprint.route('/hello')
def hello():
return "Hello to you!"
@my_blueprint.route('/goodbye')
def goodbye():
return "Goodbye!"
app.register_blueprint(my_blueprint)
if __name__ == '__main__':
app.run(debug=True)
Code Explanation
In this code, we create a Flask application and define a blueprint named my_blueprint
.
Then, using @my_blueprint.route, we add two URLs to the blueprint: one for /hello
and another for /goodbye
.
In each of these URLs, we have a handler that returns a simple text response.
Ultimately, we add the blueprint to the Flask application and run the application using app.run(debug=True)
.