Python / Python Web Development

Creating Views and Routes in Flask

This tutorial will guide you through the process of creating routes and views in Flask. We will learn how to map URLs to Python functions and how to generate responses to client r…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Introduces Python web frameworks such as Django and Flask for building web applications.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Image Converter

Convert between different image formats.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help