Image

Using Flask on the Raspberry Pi: A Comprehensive Guide

If you click our links and make a purchase, we may earn an affiliate commission. Learn more

Flask is a popular and powerful Python package that can build great web applications on the Raspberry Pi. The setup process and first steps can be difficult. Don’t worry, I will guide you through the process and we will create our first application together.

The Flask package can be installed on the Pi using the pip package manager with Python. Once the installation is complete, a basic web-based application can be deployed by initializing a Flask instance in the Python script.

In this article, we will first learn what Flask is and then install it on our Raspberry Pi. Finally, we will create our first web application in Python based on Flask. So, let’s start with the tutorial.

If you’re like me and sometimes mix up syntax between programming languages, I’ve got just the thing for you. I’ve put together a Python cheat sheet with all the essential syntax in one place, so you can keep it handy and avoid any confusion. Download it here for free!

Flask: An Open-Source Web Framework

Flask is an open-source microweb (it has minimal dependencies) Python framework. It started as an April Fool’s joke and eventually became one of the most popular web development frameworks in Python.

Image

Flask allows you to create quick and interactive web pages and its backend with minimal setup. So, all you need is the Flask package and you can quickly deploy your web application. Excited? Let’s start by seeing how easily we can install Flask on our Raspberry Pi.

Before we start, let’s just quickly review the requirements for this project:

  • In terms of hardware, you will need the following:
    • Raspberry Pi: Good News! Any Raspberry Pi works as you can install Flask on any version. I suggest using a Raspberry Pi 4 with at least 2 GB RAM, which is what I used.
    • A computer with an SD card reader (can be a Raspberry Pi with Imager on it).
      You can use a cheap USB adapter if you don’t have one (like this one on Amazon).
    • A micro-SD card to install the latest Raspberry Pi OS on the Raspberry Pi.
      Here is my current recommendation for the best performance, but any model will do for this tutorial as it aims to show you how to install and set up Tailscale on your Pi.
  • For the software, here are the requirements:
    • Raspberry Pi Imager: We will use the Imager software to flash the OS image onto our SD card.
    • Raspberry Pi OS: As always, I suggest you use the latest version of the official Raspberry Pi OS available for your Pi. Here is a tutorial that walks you through the process: How to Install (or Reinstall) Raspberry Pi OS on Your Pi.

Installing Flask on the Raspberry Pi (Python)

Using Flash with Python will make our lives much easier. Not only is coding in Python easy to learn, but the installation steps for Flash are straightforward. It just takes one command to complete the entire installation! So, let’s do it.

Verifying Python and Pip Installations

As mentioned above, we will need Python (a programming language) installed on our Pi. Luckily, Python has been preinstalled on the Pi since the original Raspberry Pi (so, in all the official OS versions).

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

Python uses a package manager called pip, which also needs to be present in our systems (this too is pre-installed).

Here are two simple commands you can execute in a terminal interface to verify that they are installed on your Raspberry Pi (‘3’ in the commands indicates we are using Python 3):
python3 --version
pip3 --version

You should see the version numbers of each package on your terminal, which means you are good to go.

Image

If, by any chance, you don’t see the above output, don’t panic. It just means that you have to install them on your Pi (may be possible if you are using any other OS). Just execute the following command depending on what you want to install:

sudo apt install python3
sudo apt install python3-pip

Are you a bit lost in the Linux command line? Check this article first for the most important commands to remember and a free downloadable cheat sheet so you can have the commands at your fingertips.

Installing the Flask Package with Pip

Once you have these packages, you can install Flask on your systems. We will use the pip package manager to do this.

However, it’s not recommended to install packages directly as it can lead to problems when you have multiple projects (look at the image below).

Image

In simple words, say you have two different projects with different package requirements, it is not a good practice to install everything in one place and use it for various applications. So, there is a concept of virtual environments, which lets us create application-specific Python instances.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

We will have a different Python running for each application. It’s a bit tricky to set up but it will help you a lot down the line. So, let’s quickly see how to set up a new environment and install Flask in it.

  • The first step is to create a directory in which we will develop our project. You can do that and move into the directory with the following command:

    mkdir flask-project && cd flask project
    Image
  • Next, we will create a new Python virtual environment here. All you need to do is run the following command:

    python3 -m venv flask_env
    Image
    This will create a new flask_env folder within the directory that contains all the necessary files for your new virtual environment.
  • Now, we need to activate this environment, which allows us to use its particular Python instance. This can be done with the following command:

    source flask_env/bin/activate
    Image
    The highlighted “flask_env” text confirms that our virtual environment has been successfully activated.
  • Finally, we can install Flask in this environment. To do that, we will use the pip package manager to install the Flask package for Python.

    pip3 install Flask

    This will take a few seconds to complete so be patient. You should see the successfully installed xyz packages statement at the end, which confirms that our installation was successful!

    Image

🛠 This tutorial doesn't work anymore? Report the issue here, so that I can update it!

If this project doesn’t work as expected on your setup, don’t worry. You can get help directly from me and other Pi users inside the RaspberryTips Community. Try it for $1 and fix it together.

Building our First Web Application

Great! Now that we have Flask on our Pi, let’s create our first web application! Let’s start by coding our first website:

Creating a New Python Project

We will create two main files for this project: “app.py” and an “index.html” file.

So, we will need a new project directory. But wait! We already have one set up and ready to go with its own Python environment (we set it up in the last section!).

So, all we need to do is create the two new files and we can move to the next section.

Image

Before you move to coding, it’s important to create a new folder named “templates” and place the index.html in that folder as the code we write will expect the file to be in that folder.

Coding our Web Application

As mentioned above, we have to code two files, so let’s do that one by one.

Flask Web Server File (app.py)

Lost in the terminal? Grab My Pi Cheat-Sheet!
Download the free PDF, keep it open, and stop wasting time on Google.
Download now

The first file we need to write will act as the brains of our web server. It will tell our browser what to show when someone types in our website’s URL (Uniform Resource Locator) (e.g., www.google.com shows the Google search engine).

We will keep things simple and write a simple web application with two pages: the homepage, and an information page showing some information about our application. So, let’s look at the entire code before breaking it down to understand it.

from flask import Flask, render_template

app = Flask(__name__)

# Homepage route
@app.route('/')
def home():
    return "Welcome to the Homepage. This is a simple Flask application."

# Info route that renders the HTML page
@app.route('/info')
def info():
    return render_template('index.html')

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

Woah! That looks tricky, right? Don’t worry, I will walk you through every line.

  • The first line allows us to use the Flask package components.
    For this tutorial, we are using the Flask and render_template components.

    from flask import Flask, render_template
  • Then, the next line initiates our Flask application.

    app = Flask(__name__)
  • Now comes the main part of the code: the first page of our web application (‘/’). This means that when someone types the URL for our website, they will see this content.

    For this tutorial, we display basic information welcoming the user.

    # Homepage route
    @app.route('/')
    def home():
    return "Welcome to the Homepage. This is a simple Flask application."

  • Next, we write the logic for our information page, which will be shown if someone goes to the following URL: <your URL>/info as indicated in the first line. For this page, we will show our HTML page (i.e. index.html) using the render_tempelate component in Flask.

    # Info route that renders the HTML page
    @app.route('/info')
    def info():
    return render_template('index.html')


    Don’t worry about the HTML file for now, I will guide you through that in the next section.
  • Finally, once everything is done, we write the final line which activates our Flask application in debug mode (this mode captures any changes we make in the application and reloads it).

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

That’s it for the app.py file. Let’s write our index.html file now.

HTML File (index.html)

HTML (Hyper Text Markup Language) is a programming language used to create webpages. Hence, it makes a lot of sense to use it to create our first web application.

For this project, we will keep things simple and create a simple webpage:

<!DOCTYPE html>
<head>
    <title>Information Page</title>
</head>
<body>
    <h1>Application Information</h1>
    <p>This is a simple Flask application to demonstrate basic routing.</p>
    <ul>
        <li>Version: 1.0.0</li>
        <li>Author: RaspberryTips</li>
        <li>Description: A minimal web app using Flask</li>
    </ul>
    <a href="/">Go back to the Homepage</a>
</body>
</html>

As before, let’s walk through the above code.

  • The first line indicates that this is an HTML file.
  • Next comes the <head> section, which contains the title of our webpage.
    This is the content that is shown on your browser tab.

    <head><title>Information Page</title></head>

    Image
  • After that comes the body content, which is shown on our webpage. For now, I have added some basic information, including a heading and a bullet point list displaying some basic information (the <ul> tag starts the list and the <li> tag is for each list item).

    <h1>Application Information</h1>
    <p>This is a simple Flask application to demonstrate basic routing.</p>
    <ul>
    <li>Version: 1.0.0</li>
    <li>Author: RaspberryTips</li>
    <li>Description: A minimal web app using Flask</li>
    </ul>

  • Finally, we have an anchor tag, which is used to link web pages together. For now, we give the user the option to return to our home page (which is indicated by the route of the href parameter, which is ‘/’ in this case). The content after the <a> tag is what is shown on the page.

    <a href="/">Go back to the Homepage</a>
  • Finally, we close our HTML and Body tags to follow the HTML coding protocol.

    </body> </html>

That’s it for the HTML file as well. Once we have both these files, we are ready to deploy and test our application!

Deploying and Testing our Application

Once you have written the code for both these files on your Raspberry Pi, they should look something like this.

Image
Lost in the terminal? Grab My Pi Cheat-Sheet!
Download the free PDF, keep it open, and stop wasting time on Google.
Download now

Make sure that the structure of the directory is as I mentioned before (the index.html file is placed in the templates folder). Otherwise, you will see an error when you try to load the information page. To deploy our web app, you have to execute the following commands:

cd <project directory>
python3 app.py

Image

This will start your Flask application on port 5000, which is the default port for Flask. Now, you should be able to access your application with the URL: http://localhost:5000/. Try to open it on your browser and see the magic!

Image

If you see this screen, pat yourself on the back! You have successfully deployed your first Flask web app on your Raspberry Pi. If you change the URL to localhost:5000/info, you should see the content we wrote in our index.html file.

Image

This marks the end of this section and this tutorial. This is just the tip of the iceberg when it comes to Flask development on the Raspberry Pi. You can create more complex projects like a fully functional blogging website, hosted on your Pi!

Thank you for reading this article. See you in the next one!

Whenever you’re ready, here are other ways I can help you:

Test Your Raspberry Pi Level (Free): Not sure why everything takes so long on your Raspberry Pi? Take this free 3-minute assessment and see what’s causing the problems.

The RaspberryTips Community: Need help or want to discuss your Raspberry Pi projects with others who actually get it? Join the RaspberryTips Community and get access to private forums, exclusive lessons, and direct help (try it for just $1).

Master your Raspberry Pi in 30 days: If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.

Master Python on Raspberry Pi: Create, understand, and improve any Python script for your Raspberry Pi. Learn the essentials step-by-step without losing time understanding useless concepts.

You can also find all my recommendations for tools and hardware on this page.

Similar Posts