Routes
In Flask, routes are the URLs or endpoints that define how a web application responds to client requests. A route maps a specific URL to a Python function (known as a view function), which processes the request and generates a response. Routes are a fundamental part of Flask's design, enabling developers to define the behavior of their web application.
What are Routes?
A route in Flask is essentially a mapping between a URL and a function. The function is executed whenever a request is made to the associated URL. This URL-to-function mapping is maintained by Flask's application object.
For example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the homepage!"
In the example above, the route '/'
maps to the home
function. When a client accesses the root URL (/
), the home
function is executed, and its return value is sent as the HTTP response.
The @app.route
Decorator
The @app.route
decorator is used to define a route in Flask. It binds a URL to a Python function. This decorator is a part of the Flask app
object.
Syntax
@app.route(route, methods=['GET'], **options)
route
: The URL path (e.g.,/home
,/about
,/user/<id>
).methods
: Specifies the HTTP methods allowed for this route (default:['GET']
).options
: Additional options for the route, likestrict_slashes
.
Key Features of Flask Routes
Basic Routes
A basic route responds to a specific URL. For example:
@app.route('/')
def home():
return "Hello, Flask!"
- When a client accesses the root URL
/
, thehome
function is executed.
Dynamic Routing
Dynamic routes allow the inclusion of variables in the URL. These variables can be passed to the view function as arguments.
-
Syntax for Dynamic Routing:
@app.route('/<variable_name>')
def function_name(variable_name):
... -
Example:
@app.route('/user/<username>')
def show_user(username):
return f"Hello, {username}!"- URL
/user/abhishek
will respond with "Hello, abhishek!"
- URL
-
Type Converters: Flask supports type converters to enforce variable types in dynamic routes:
<string>
: Default, matches strings.<int>
: Matches integers.<float>
: Matches floating-point numbers.<path>
: Matches a string containing slashes (/
).<uuid>
: Matches a UUID string.
Example with Type Converters:
@app.route('/product/<int:product_id>')
def show_product(product_id):
return f"Product ID: {product_id}"
HTTP Methods
Routes can specify the allowed HTTP methods (e.g., GET
, POST
, PUT
, DELETE
).
-
Specifying Methods:
@app.route('/submit', methods=['POST'])
def submit():
return "Form submitted!" -
Handling Multiple Methods:
@app.route('/form', methods=['GET', 'POST'])
def form():
if request.method == 'POST':
return "Form submitted!"
return "Form page"