Creating a Basic Raspberry Pi Web Server with Python and Flask


Description

This project will provide you with the steps to create a basic Raspberry Pi Web Server using Python and Flask. You’ll be amazed at how little code it takes to get started!

This can open the door to limitless possibilities with your Pi. You can connect physical devices to your Pi’s GPIO pins and control them directly through the browser or with web services (i.e., a Smart Pet Feeder). You can create a ‘Twitter-bot’ and periodically post pictures you take with a camera attached to your Pi (i.e., a Pet Cam). You could interface with smart devices and control them and show their current status (i.e., a Smart Home Dashboard).

There’s really no limit!

Parameters

This is some information about this project and the conditions under which it was done. If you try to replicate it in the future and it doesn’t work, you can evaluate these parameters to see if any changes between these and your configuration might have impacted your results. An example might be changes to future versions of Python or Flask.

  • Date: July 16, 2021
  • Skill: Beginner
  • Raspberry Pi Model(s): Zero-W, 3B+, 4B
  • OS: Raspberry Pi OS version 10 (Buster)
  • Python Version: 3.7.3
  • Flask Version: 1.0.2

Steps

  1. If you’re starting from scratch, then you’ll need to format a Micro-SD Card and install Raspberry Pi OS. You can follow these steps if needed:  SD Card Setup

Otherwise, just make sure everything is up to date by opening Terminal on your Pi and typing the following two commands:

sudo apt-get update
sudo apt-get upgrade
  1. Open Terminal on your Pi and install Flask by typing in the following command (may already be installed by default, but won’t hurt anything):
sudo pip3 install flask

Open GeanyThonny, or your favorite Python editor on your Pi and type in the following lines of code:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return 'Success!'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
  1. That’s all you need to create a basic web server using Flask!

Notice the @app.route('/') line. That tells Flask to execute the code following it when the root ‘/’ path is requested from the browser. In this case, we have defined the index() function with the line def index():

Also notice the line app.run(debug=True, host='0.0.0.0', port=5000). The debug=True part tells Flask that we are still working on the server and to auto-restart as we save changes to the file. Change this to False once you have a stable version. The host='0.0.0.0' part tells Flask to make this server available to everyone on the network and  port=5000 tells Flask to make this server available on port 5000, which is the default port for Flask.

  1. Save the file to:/home/pi/sample/sample.py
  1. Press Play in the Thonny editor and correct any erors. If you’re not using Thonny, open the Terminal and change to the directory of your project (cd /home/pi/sample). Then type  python3 sample.py to run the server. If all goes well, it should look something like this:

Your server is now running and listening for requests!

  1. Once the server successfully starts, test it by entering the address of the Pi in a browser followed by the port number and our path ‘/’. (i.e., http://192.168.2.221:5000/). This can be a browser on any device connected to the same network as your Pi. If you don’t know the IP address of your Pi, open another Terminal window and enter the command hostname -I (that’s a capital ‘i’).
Successful call to web server
  1. Now we’ll create a simple HTML file to return to the browser. I use Geany, but you can use any text editor. Enter the following:
<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      background-color: lightblue;
      color: blue;
    }
  </style>
</head>

<body>
  <h1>My Webserver!</h1>
</body>
</html>

Save the file to: /home/pi/sample/templates/index.html
The /templates directory is the default location where Flask looks for HTML files.

Now edit your server code (sample.py) and change your return statement from return ‘Success!’ to the following: return render_template('index.html')

It should now look like this:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Save those changes and refresh the browser and you should see your index.html results.

Returning HTML/CSS

Notice we added a little color with some CSS stylesheet coding as well.

  1. That’s how simple it is to get a basic Flask server running! In a future project I’ll show you how to create a route in your server to gather current information about the server and pass that information as parameters to an HTML page.

Summary

You should have been able to create a basic Flask web server running on a Raspberry Pi. You can use this as a starting point and continue to build out the features and functions that you need.

In the next project I’ll cover how to pass dynamic content from your server as parameter to your HTML. I will also post future projects where I show you other features that I think might help you on your journey as well.

Learn More

Raspberry Pi / Raspberry Pi OS

Python / HTML / CSS

Flask

Leave a Comment

Your email address will not be published. Required fields are marked *