Creating Views and Routes in Flask

Tutorial 2 of 5

1. Introduction

Goal of the Tutorial

The aim of this tutorial is to guide you on how to create views and routes in Flask, a lightweight and powerful Python web framework.

Learning Outcomes

By the end of this tutorial, you will:

  1. Understand what routes and views are in Flask.
  2. Learn how to map URLs to Python functions (routing).
  3. Learn how to generate responses to client requests (views).

Prerequisites

Before starting, you should have:

  1. Basic knowledge of Python.
  2. Flask installed on your system. If not, check out this Flask Installation Guide.

2. Step-by-Step Guide

Routes in Flask

In Flask, a route is a URL pattern that is used to find the appropriate view function for a particular URL. A route is defined using the @app.route() decorator followed by a function that returns a response.

Views in Flask

A view in Flask is a Python function that handles a client request and generates a response. This response can be a web page (HTML), a redirect, a 404 error, an XML document, an image, or any other type of response.

3. Code Examples

Example 1: Basic Route and View

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run(debug=True)
  • from flask import Flask - This line imports the Flask module and creates a Flask web server from the Flask module.
  • app = Flask(__name__) - This line creates a new web application called "app".
  • @app.route('/') - This line is a decorator that tells Flask what URL should trigger the home function. The '/' URL corresponds to the main or home page.
  • def home(): return 'Hello, Flask!' - This is the view function named home. It returns the string 'Hello, Flask!' which is displayed in the user's browser when they navigate to the home page.
  • if __name__ == '__main__': app.run(debug=True) - This line ensures the server only runs if the script is executed directly from the Python interpreter and not used as an imported module.

The expected output when you navigate to the home page (usually 'localhost:5000/' if running locally) is:

Hello, Flask!

Example 2: Multiple Routes

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the Home Page!'

@app.route('/about')
def about():
    return 'Welcome to the About Page!'

if __name__ == '__main__':
    app.run(debug=True)
  • The @app.route('/about') line defines a new route for the URL '/about'.
  • The def about(): return 'Welcome to the About Page!' line defines a new view function that returns a different message.

The expected output when you navigate to the 'about' page (usually 'localhost:5000/about' if running locally) is:

Welcome to the About Page!

4. Summary

In this tutorial, we have learned about routes and views in Flask. We have seen how to define routes using the @app.route() decorator and how to create view functions that generate responses to client requests.

For further learning, you can explore how to:

  • Handle dynamic URLs with variable parts.
  • Use different HTTP methods (GET, POST).
  • Serve static files (CSS, JavaScript, images).

You can find additional resources in the Flask Documentation.

5. Practice Exercises

  1. Exercise: Create a new route for the URL '/contact' and return the string 'Welcome to the Contact Page!'.

Solution:

python @app.route('/contact') def contact(): return 'Welcome to the Contact Page!'

  1. Exercise: Create a new route for the URL '/user/' that displays a personalized welcome message.

Solution:

python @app.route('/user/<username>') def user(username): return 'Welcome, {}!'.format(username)

Remember, the key to mastering Flask (like any programming skill) is consistent practice. Happy coding!