Introduction
The route decorator connects a web address to a function in your Flask app. It tells the app what to do when someone visits a specific URL.
The route decorator connects a web address to a function in your Flask app. It tells the app what to do when someone visits a specific URL.
@app.route('/path') def function_name(): return 'response'
@app.route('/') def home(): return 'Welcome to the homepage!'
@app.route('/about') def about(): return 'About us page'
@app.route('/user/<username>') def show_user(username): return f'User: {username}'
This Flask app has two routes: the homepage at '/' and a greeting page at '/greet/<name>'. Visiting '/greet/Alice' will show 'Hello, Alice!'.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, this is the homepage!' @app.route('/greet/<name>') def greet(name): return f'Hello, {name}!' if __name__ == '__main__': app.run(debug=True)
Use @app.route() to connect URLs to functions easily.
Variable parts in URLs use <> brackets, like <username>.
Flask matches routes in the order they are defined, so be careful with overlapping paths.
@app.route links a URL path to a function in Flask.
It helps your app respond to different web addresses.
You can use fixed or variable URL parts with it.
@app.route decorator do in a Flask application?@app.route is used to link a URL path to a function in Flask./home in Flask?@app.route('/home') placed immediately before a function definition./user/42 given this Flask code?@app.route('/user/<int:id>')
def show_user(id):
return f"User ID is {id}"/user/<int:id> captures an integer from the URL and passes it as the argument id to the function.id value inserted using an f-string.@app.route('/hello')
def hello():
print('Hello World')
return 'Hello!'print and return are not indented under def hello():./profile/john and returns Hello, john!. Which code correctly achieves this?username as a string variable using <username> in the URL.username as a parameter and return the greeting using an f-string.Pass the test and this pattern moves unknown