Flask – Variable Rules
It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is set apart as <variable-name>. It is passed as a keyword argument to the capacity with which the standard is associated. In the following model, the standard parameter of course() decorator contains
from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True)
The following output will be displayed in the browser.
The given number is used as argument to the show_blog() function. The browser displays the following output −
Blog Number 11
Enter this URL in the browser − http://localhost:5000/rev/1.1
The revision() function takes up the floating point number as argument. The following result appears in the browser window −
Revision Number 1.100000
The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache.
Consider the rules defined in the following script −
from flask import Flask app = Flask(__name__) @app.route('/flask') def hello_flask(): return 'Hello Flask' @app.route('/python/') def hello_python(): return 'Hello Python' if __name__ == '__main__': app.run()Both the rules appear similar but in the second rule, trailing slash (/) is used. As a result, it becomes a canonical URL. Hence, using /python or /python/ returns the same output. However, in case of the first rule, /flask/ URL results in 404 Not Found page.