Flask Tutorial Part 4: Routing and URL Building
๐ฆ What is Routing in Flask?
Routing in Flask means mapping a URL to a function. Flask uses a Python decorator @app.route()
to define URL routes. Each route is associated with a view function, which is executed when the specified URL is requested. This makes it possible for Flask to handle different requests and return the appropriate response for each one.
๐งช Basic Routing Example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to DarchumsTech!"
๐ Dynamic Routing
You can capture parts of the URL and pass them as arguments to your view function:
@app.route("/user/<username>")
def show_user(username):
return f"Hello, {username}!"
๐ URL Building with url_for()
Flask provides a url_for()
function to generate URLs using function names rather than hardcoding them:
from flask import url_for
@app.route("/dashboard")
def dashboard():
return "Dashboard Page"
@app.route("/go_to_dashboard")
def go_to_dashboard():
return redirect(url_for('dashboard'))
๐ Summary
- Use
@app.route()
to map URLs to Python functions. - Use angle brackets
<>
to capture dynamic values in routes. url_for()
helps you generate URLs programmatically.
Comments
Post a Comment