0
0
Flaskframework~5 mins

Why routing is Flask's core

Choose your learning style9 modes available
Introduction

Routing tells Flask what to do when someone visits a web address. It connects web addresses to the right code to run.

When you want to show different pages on your website.
When you want to handle user actions like clicking buttons or submitting forms.
When you want to organize your website so each URL does something specific.
When you want to build an API that responds to different web requests.
When you want to control what content users see based on the URL they visit.
Syntax
Flask
@app.route('/path')
def function_name():
    return 'response'
Use @app.route to link a URL path to a function.
The function runs when someone visits that URL and sends back a response.
Examples
This shows a message when someone visits the main page.
Flask
@app.route('/')
def home():
    return 'Welcome to the homepage!'
This shows an about page at the URL '/about'.
Flask
@app.route('/about')
def about():
    return 'About us page'
This shows a personalized greeting using a part of the URL.
Flask
@app.route('/user/<name>')
def user(name):
    return f'Hello, {name}!'
Sample Program

This Flask app has two routes: the homepage and a greeting page that uses a name from the URL.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.