Introduction
Routing tells Flask what to do when someone visits a web address. It connects web addresses to the right code to run.
Routing tells Flask what to do when someone visits a web address. It connects web addresses to the right code to run.
@app.route('/path') def function_name(): return 'response'
@app.route to link a URL path to a function.@app.route('/') def home(): return 'Welcome to the homepage!'
@app.route('/about') def about(): return 'About us page'
@app.route('/user/<name>') def user(name): return f'Hello, {name}!'
This Flask app has two routes: the homepage and a greeting page that uses a name from the URL.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the homepage!' @app.route('/hello/<name>') def hello(name): return f'Hello, {name}!' if __name__ == '__main__': app.run(debug=True)
Routing is how Flask knows what code to run for each web address.
Use variable parts in routes to make dynamic pages.
Routes must be unique; two functions cannot use the same URL path.
Routing connects URLs to Python functions in Flask.
It lets you create different pages and responses for your website.
Dynamic routes let you use parts of the URL as input to your functions.
/user/42 in this Flask app?@app.route('/user/<int:id>')
def show_user(id):
return f'User ID is {id}'@app.route('/hello')
def hello():
print('Hello World')
return 'Hello!'Pass the test and this pattern moves unknown