Install Flask + Raspberry Pi + Python 3 2019

This is a tutorial on how to setup and run a Flask server on your Raspberry Pi.

1. Update your Raspberry Pi + Install Python

The following commands will download and install python.

sudo apt-get update -y
sudo apt-get install build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev -y
wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz
tar xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make -j 4
sudo make altinstall
cd ..
sudo rm -r Python-3.7.0
rm Python-3.7.0.tar.xz
sudo apt-get --purge remove build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev -y
sudo apt-get autoremove -y
sudo apt-get clean

2. Create a virtual environment

This will setup a virtual environment which allows you to manage dependencies such as Flask without having to install them globally (aka sudo..)

cd ~/
mkdir flask-app
cd flask-app
python3.7 -m venv venv
source venv/bin/activate
pip install flask
pip install requests

3. Create the app

Create an app.py file. and check your directory structure

touch app.py
ls -latr
Your file system should now look like this in ~/home/pi/flask-app/

4. Create the app

We need to edit the main app.py file so that it starts up a Flask application. For more information about Flask follow this link.

nano app.py

########################################
# Code below here goes into app.py
########################################
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    print("Starting Flask server on port 5000!")
    app.run(host='0.0.0.0', port='5000')

Close the nano editor by pressing CTRL-X and then CTRL-Y to save. Now we need to get your Raspberry Pi’s hostname by running the command

hostname -I

Since our app is running on port 5000, we will need to go to the address above plus :5000. The address of my pi is http://192.168.1.116:5000/

5. Start up the app!

You can now startup the app by running

python app.py

You should now be able to view your app at the address from above http://your-pi-ip-address:5000/

There is a lot you can do with Flask and if you’d like more tutorials feel free to comment below.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.