Using Flask on a Raspberry Pi with MongoDB (Part 1)

Introduction

In this article series, we’ll show you how to set up a Flask web app, written in Python, on a Raspberry Pi. Our app will be using MongoDB as its backend database. This first installment of the series will cover the initial setup and configuration needed for Flask, Raspberry Pi and MongoDB. By the end of this article, you should have your own Raspberry Pi web server running on your local network; this web server will be able to return MongoDB documents to a browser on any device connected to the network.

Prerequisites

This tutorial assumes that you already know how to set up your Raspberry Pi and that you’ve already installed or copied Linux to its SD card.

The article also assumes that you’re running a Raspbian flavor of Linux for the Raspberry Pi. If you’re running another operating system on your Pi, some of the commands in this article may not work.

Enable SSH on the Raspberry Pi

Before you can install packages and set up your Pi device as a local web server, you must first hook it up to a TV or monitor and use the Raspbian GUI desktop to enable SSH. Make sure that the Pi’s wireless internet connection is working, or connect it to your router or switch using a Cat5E cable.

Screenshot of enabling SSH in Raspbian for a Flask Raspberry Pi MongoDB web app

NOTE: Older versions of Raspbian may have SSH enabled by default.

To enable SSH, click the Raspberry icon in the upper left-hand corner of the desktop and navigate to the Preferences menu. Click the Raspberry Pi Configuration submenu. Once the Configuration modal window pops up, click the Interfaces tab, followed by the Enable radio button for SSH.

You may need to restart the Raspberry Pi device for the changes to take effect.

Find the Raspberry Pi’s Local IP Address

Open a new Linux or macOS terminal on another computer connected to your local network and use the arp command to list all of the devices connected to your network:

1
arp -a

NOTE: You can also use the ifconfig command in a UNIX terminal to get your device’s local gateway IP address. The command ip r | grep default also works in Linux.

The output of this command will contain the IP addresses for the devices along with their unique, 12-digit, hexadecimal MAC addresses. Your Raspberry Pi device should have a MAC address that starts with either dc or b8.

SSH into the Raspberry Pi

At this point, we’re ready to use the SSH access that we enabled in an earlier section. Use the local IP address for the Raspberry Pi that’s connected on your local network to SSH into the device. Let’s look at an example of how you can use the ssh command to connect to the Raspberry Pi using Pi’s local IP address and the built-in pi username:

1
ssh pi@192.168.123.45

NOTE: All routers generally start with a default IP address of 192.168; however, it may vary slightly depending on your router or switch’s IP address. The last two digits of the address are assigned to a specific device, but that value can change when other devices are connected, or if the router has been reset.

Install PIP for Python 3

You’ll need to make sure Python 3 is installed and working before you can build anything using Flask, Raspberry Pi and MongoDB. It’s better not to use Python 2.7 since it’s been deprecated. Use the python3 -V or which python3 commands to get more information about your Python 3 installation on Raspbian.

Next, you’ll need to install the PyMongo Python driver for MongoDB using the PIP package manager on the Raspberry Pi. Use the pip3 --version command to make sure PIP3 is installed; if you need to install it on your Pi, use the following command:

1
sudo apt update && sudo apt install python3-pip

Install PyMongo on the Raspberry Pi

Once PIP3 is finished installing, you can install the PyMongo Python driver for MongoDB using the pip3 install command:

1
pip3 install pymongo

WARNING: If you’re using an older version of MongoDB, then you’ll also have to use an older version of the PyMongo driver. You can use the pip3 uninstall pymongo command to uninstall your existing Python module, and then reinstall an older version instead. For MongoDB v2.4, you’ll want to use v2.9.5 of the PyMongo driver and install it with pip3 install pymongo==2.9.5.

Install the Flask Web Framework for Python 3

The final package we’ll need to install with PIP is the Flask library for the Python-based web framework. Use the command shown below to install the latest version of Flask for Python 3:

1
pip3 install flask

Install a Web Server for the Raspberry Pi

It’s wise to have a backup web server, such as Apache or Nginx, installed on your Raspberry Pi in case the Flask app crashes. Use the following command to install Nginx on the Raspberry Pi:

1
sudo apt-get install nginx

To start the Nginx service, you can use this command:

1
sudo /etc/init.d/nginx start

The command will return a response of [ ok ] Starting nginx (via systemctl): nginx.service.

If you’d prefer to use an Apache web server, you’d use the following command:

1
sudo apt install apache2

After you install your web server, navigate to your Raspberry Pi’s IP address (http:\\192.168.XXX.xx) in a browser on your development machine. If you see a “welcome” page, you can be sure that the web server is working.

Screenshot of the Nginx welcome page for the Flask Raspberry Pi MongoDB web app

Install MongoDB on Raspbian

Next, let’s install the ARM architecture release of MongoDB. We’ll use the following APT-GET install command:

1
sudo apt-get install mongodb

Because the Raspberry Pi single-board computer uses the ARM architecture, many newer, supported versions of MongoDB will not work on it. Depending on your particular Raspbian distribution, you may have to use an older version of MongoDB, such as v2.4.

You’ll also need to install the MongoDB server library using APT-GET:

1
sudo apt-get install mongodb-server

If you’re not sure which version of MongoDB is installed, use the mongod --version command, while connected to the Pi with a secure shell. This command will return your exact version number

Build MongoDB from Source on a Raspberry Pi

As of January 2020, there is no Ubuntu release of MongoDB for the latest Raspbian Buster (version 10). However, if you’re using an older Bionic Beaver version of Ubuntu, you may be able to install v4.2 by building it from source. Let’s take a look at the build process in more detail:

Install MongoDB 4.2 on Raspbian Bionic Beaver

First, you’ll need to get the PGP key for the MongoDB v4.2 repository:

1
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -

Next, use the echo command to append the repository link and list the file to your Raspbian’s /etc/apt/sources.list.d directory:

1
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

Finally, you’ll need to update and install MongoDB from the newly-added Debian repository:

1
sudo apt-get update && sudo apt-get install mongodb-org

If you don’t want to build MongoDB from source or install an older version, another option would be to install Docker and run a newer version of MongoDB in a containerized environment on the Raspberry Pi.

Start MongoDB

At this point, you should be able to start the MongoDB service; however, there’s still some configuration that needs to be done. Use the following systemctl command to start the MongoDB service:

1
sudo systemctl start mongodb

You can use the enable option to enable the service so that it starts whenever you boot the Raspberry Pi:

1
sudo systemctl enable mongodb

Finally, use the service command to initialize and set up your MongoDB service by authenticating a user:

1
service mongodb start

After you complete the configuration, execute the mongod command to make sure that the service is running. If you get an error saying: “ERROR: dbpath (/data/db/) does not exist“, you’ll need to set up the MongoDB database path first.

The command shown below can be used to create the /date/db directory and subdirectory. Then, you can grant ownership of the directory to the pi user with the chown command:

1
sudo mkdir -p /data/db && sudo chown pi /data/db

NOTE: The -p, or “parent”, flag allows you to create nested directories inside of a parent directory without having to execute multiple mkdir commands. You’ll need to execute this command with sudo privileges since you’re modifying a key system path.

Depending on your version of MongoDB, you may also need to set the --storageEngine option for the /data/db path. You can do this with the following command:

1
2
mongod --storageEngine=mmapv1 --dbpath /data/db
--storageEngine=mmapv1

Configure the Raspbian MongoDB server

The last thing we’ll need to do to get MongoDB working is to configure the mongodb.conf file so that all IP addresses on the network can access the server. Use a text-based editor like nano to edit the file:

1
sudo nano /etc/mongodb.conf

When you’re editing the file, make sure to comment out and replace the line that says bind_ip = 127.0.0.1 with bind_ip = 0.0.0.0.

Screenshot of the mongodb.conf file for the Flask Raspberry Pi MongoDB web app

After you make your changes, press CTRL+O to write the changes to the file and CTRL+X to exit nano.

Now, try restarting the service with sudo service mongodb restart. If everything is working as expected, you should be able to execute the curl localhost:27017 command and have it return the following response:

1
It looks like you are trying to access MongoDB over HTTP on the native driver port.

Connect to MongoDB

MongoDB comes with the Mongo shell interface pre-installed. We can use this command-line interface to perform queries and modify MongoDB data stored in collections and databases.

Connecting to mongo Shell for a Flask Raspberry Pi MongoDB web app

To access the Mongo shell, type mongo in your SSH terminal session. When you’re done, just type quit() to exit the client interface. You can close the SSH connection by typing exit and pressing return, or you can execute the sudo shutdown -h now command to shut down your Raspberry Pi.

Conclusion

We’ve covered a lot of ground in this first installment of our tutorial on using Flask, Raspberry Pi and MongoDB together. In this article, we got the Pi’s web server and MongoDB database running, so we’re all set up and ready to run our Flask web application. Check out the second part of this series to see how you can easily build a Flask web application for your Pi that can serve up MongoDB documents to a front-end user in a browser.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.