Dynamic Routing in Flask


Dynamic routing in Flask allows you to define routes with dynamic parts in the URL, which allows for more flexible and parameterized routing in your application.

Dynamic Routers :

  • A variable in the route<variable>
  • A parameter passed in to the function
"""
	Eg:
	 
	@app.route('/page/<name>')
	def pageMethod(name):
		-------
		-------
		-------
		return ...;
	"""

Here's an example of dynamic routing in Flask using PyCharm as the code editor:

Source Code

from flask import Flask
	 
	app = Flask(__name__)
	 
	@app.route('/') 
	def index():
		return '<h1>Tutor joes</h1><p>Learn More Be Smart</p>'
	 
	@app.route('/about')
	def about():
		return '<h3>Tutor Joes Computer Education Salem</h3>' 
	 
	@app.route('/contact')
	def contact():
		return '<h3>Contact Us</h3>' 
	 
	@app.route('/users/<name>')
	def user(name):
		return "<h3>Welcome {}</h3>".formate(name)
	 
	if __name__ == '__main__':
		app.run(debug=True)	
	 

The code you provided is correct and implements dynamic routing in Flask. It defines four routes:

/: Maps to the index() function, which returns an HTML response with a heading and a paragraph.


index output

/about: Maps to the about() function, which returns an HTML response with a heading.


about output

/contact: Maps to the contact() function, which returns an HTML response with a heading.


contact output

/users/<name>: Maps to the user() function, which takes a parameter name from the URL and returns an HTML response with a welcome message containing the value of name.


output

When you run this Flask application and access these URLs in a web browser or through an HTTP request, Flask will call the corresponding functions and return the appropriate HTML responses. For example, if you access "http://localhost:5000/users/Tutor joes", Flask will call the user() function with "john" as the value for the name parameter, and the function will return an HTML response with the message "Welcome Tutor joes".