Flask Routing
What is routing in Flask?
Routing in Flask refers to mapping URLs to specific view functions. When a user accesses a particular URL, Flask triggers the corresponding function associated with that route, which generates a response. Routes are defined using the @app.route() decorator, and Flask uses this to determine which view function to call based on the request URL.
How do you define a route in Flask?
You define a route in Flask using the @app.route() decorator. This decorator binds a URL to a view function that handles requests to that URL. The function returns the content or data that is displayed when the route is accessed.
Example of defining a route:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Home Page"
In this example, the @app.route() decorator defines a route for the root URL /, and the home() function is executed when the route is accessed.
How do you define a route with a dynamic URL parameter?
You can define a route with a dynamic URL parameter by using angle brackets <> in the route definition. Flask captures the value inside the brackets and passes it as an argument to the view function.
Example of a route with a dynamic URL parameter:
@app.route('/user/<username>')
def show_user(username):
return f"User: {username}"
In this example, the <username> is a dynamic URL parameter, and its value is passed to the show_user() function when a user visits the /user/<username> route.
What data types can be used in Flask dynamic routes?
Flask allows you to specify the data type of dynamic route parameters. By default, Flask captures all parameters as strings, but you can specify other types like integers and floats. The supported types are:
string: Default, accepts any text without a slash.int: Accepts integers only.float: Accepts floating-point numbers.path: Similar tostringbut accepts slashes as part of the value.
Example of using data types in dynamic routes:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f"Post ID: {post_id}"
@app.route('/price/<float:amount>')
def show_price(amount):
return f"Price: {amount}"
In this example, <int:post_id> captures an integer, and <float:amount> captures a floating-point number from the URL.
How do you handle multiple routes for a single view in Flask?
You can handle multiple routes for a single view by using multiple @app.route() decorators for the same view function. This allows the same function to be triggered by different URLs.
Example of handling multiple routes:
@app.route('/')
@app.route('/home')
def home():
return "Welcome to the Home Page"
In this example, both the root URL / and /home trigger the home() view function and return the same response.
What are HTTP methods in Flask, and how do you handle them in routes?
HTTP methods define the type of action a request wants to perform, such as retrieving data (GET) or submitting data (POST). By default, Flask routes handle only GET requests. To handle multiple HTTP methods like POST, PUT, and DELETE, you specify them using the methods argument in the @app.route() decorator.
Example of handling multiple HTTP methods:
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
return "Form submitted"
return "Submit Form"
In this example, the /submit route handles both GET and POST requests. When a POST request is received, it returns "Form submitted", otherwise, it returns "Submit Form".
How do you redirect a user to a different route in Flask?
You can redirect a user to a different route in Flask using the redirect() function. This function takes the target URL or route as an argument and redirects the user to that location.
Example of redirecting to another route:
from flask import redirect
@app.route('/old-home')
def old_home():
return redirect('/')
@app.route('/')
def home():
return "Welcome to the Home Page"
In this example, accessing the /old-home route redirects the user to the root URL /, which displays the home page.
How do you generate URLs dynamically in Flask?
In Flask, you can dynamically generate URLs for routes using the url_for() function. This function takes the name of the view function as an argument and returns the corresponding URL. It is useful for creating links or redirects without hardcoding URLs.
Example of using url_for():
from flask import url_for
@app.route('/')
def home():
return f"Go to the About Page."
@app.route('/about')
def about():
return "About Page"
In this example, the url_for('about') function dynamically generates the URL for the about() view, which is used in an HTML link.
How do you handle custom 404 error pages in Flask?
You can handle custom 404 error pages in Flask by creating a view function for the 404 error and using the @app.errorhandler() decorator to catch the error. This allows you to define a user-friendly error page when the requested route is not found.
Example of handling a custom 404 error page:
@app.errorhandler(404)
def page_not_found(e):
return "Sorry, page not found!", 404
In this example, when a user tries to access a non-existent route, the custom page_not_found() function is triggered, and it returns a custom 404 error message.
What is the url_for() function, and why is it useful?
The url_for() function in Flask is used to dynamically generate URLs for routes based on the view function name. It is useful because it abstracts the URL generation process, making your code more flexible and maintainable. This way, if the URL structure changes, you only need to update the route definitions, not every hardcoded URL in your templates or code.
Example of generating a URL dynamically:
from flask import url_for
@app.route('/user/<username>')
def profile(username):
return f"Profile of {username}"
# Generate URL for the 'profile' view with a specific username
profile_url = url_for('profile', username='JohnDoe')
In this example, url_for('profile', username='JohnDoe') dynamically generates the URL for the profile() view with the username "JohnDoe".
How do you define route endpoints in Flask?
In Flask, the @app.route() decorator assigns an endpoint name to a view function. By default, the endpoint is the name of the view function, but you can specify a custom endpoint name by using the endpoint argument in @app.route(). The endpoint is used in conjunction with the url_for() function to dynamically generate URLs.
Example of specifying a custom endpoint:
@app.route('/about-us', endpoint='about')
def about_page():
return "About Us Page"
# Generate URL for the custom 'about' endpoint
url_for('about')
In this example, the about_page() function is assigned the custom endpoint name about. The url_for('about') function generates the URL /about-us.