Python > Web Development with Python > Flask > Routing

Basic Flask Routing Example

This snippet demonstrates how to define basic routes in a Flask application. Routes determine which function should be executed when a user visits a specific URL on your website.

Understanding Flask Routes

In Flask, routing is the process of mapping URLs to specific functions. When a user visits a certain URL, Flask 'routes' the request to the associated function, which then generates the response (usually an HTML page or some data). We use the @app.route() decorator to bind a function to a URL.

Code Example

This code defines three routes:

  1. The root route ('/') which displays 'Hello, World!'.
  2. The '/about' route which displays a simple about page.
  3. The '/user/' route which displays a user profile, dynamically taking the username from the URL.
The app.run(debug=True) line starts the Flask development server in debug mode. Debug mode provides helpful error messages and automatically reloads the server when you make changes to the code.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return '<h1>Hello, World!</h1>'

@app.route('/about')
def about():
    return '<h2>About Page</h2><p>This is a simple about page.</p>'

@app.route('/user/<username>')
def user_profile(username):
    return f'<h3>User: {username}</h3>'

if __name__ == '__main__':
    app.run(debug=True)

Concepts Behind the Snippet

This example illustrates the fundamental concepts of routing in Flask: URL mapping, function association using decorators, and dynamic URL parameters using angle brackets ().

Real-Life Use Case

Imagine building an e-commerce website. You would use routes to handle different product pages (/product/123), category pages (/category/electronics), the shopping cart page (/cart), and the checkout page (/checkout). Each route would be associated with a function that renders the appropriate content for that page.

Best Practices

  • Keep route names descriptive and consistent.
  • Use dynamic routes (/) for resources that vary.
  • Organize your routes logically within your application. For larger applications, consider using blueprints to modularize routes.

Interview Tip

Be prepared to explain how routing works in Flask and how you would use it to design the URL structure of a web application. Understand the purpose of the @app.route() decorator and how to extract parameters from the URL.

When to Use Them

Use Flask routes whenever you need to map specific URLs to actions within your web application. This is the core mechanism for handling web requests.

Alternatives

Alternatives to using the @app.route decorator directly include using Flask's method views or employing blueprints to organize routes into logical modules, especially for larger applications. Some frameworks, like FastAPI, offer a different routing syntax.

Pros

  • Simple and intuitive syntax
  • Easy to understand and use
  • Allows for dynamic URL parameters

Cons

  • Can become difficult to manage for very large applications without proper organization (e.g., using blueprints).
  • Tight coupling of URL structure to function names.

FAQ

  • What is the purpose of the @app.route() decorator?

    The @app.route() decorator is used to bind a URL to a specific function. When a user visits that URL, the associated function will be executed.
  • How do I pass parameters in a URL?

    You can use angle brackets (<>) in the URL to define parameters. For example, @app.route('/user/') will capture the username from the URL and pass it as an argument to the user_profile function.
  • What does debug=True do in app.run()?

    Setting debug=True enables debug mode. This provides helpful error messages in the browser and automatically reloads the server when you make changes to your code, which is useful during development.