Sunday, December 23, 2018

How to Create Flask Server with Raspberry Pi

On this very basic tutorial, we gonna create a simple Flask Server with Raspberry Pi. Flask is python microframework which allows you to create a web based applications.

This time, we'll install Flask and using NGINX as the default webserver, altough the similar way can be reproduced using Apache.

Prepare your SD Card and burn the latest Raspbian Image onto the SD card using the tool like 'Etcher' or 'dd' command in Linux/MacOS.

Power on you raspberry pi, and take a moment, be sure your Raspberry Pi is connected to Internet, through Wi-Fi or LAN. Then update the repository and packages on Raspberry Pi with this command:

sudo apt-get update

Install the required software, like NGINX, pip3 (python installer) and uWSGI (micro-WSGI):

sudo apt-get install nginx
sudo apt-get install python3-pip
sudo pip3 install uwsgi

To install Flask Microframework, use the pip command:

sudo pip3 install flask

Create Flask App and Nginx Configuration

In your home directory, create new directory for flask app example, called 'flask'. Create new file, called '' with nano containing this example script:

from flask import Flask
app = Flask(__name__)

def index():
return "<html><body><h1>Test site running under Flask</h1></body></html>"

if __name__ == "__main__":'',debug=True)

then, test your script with uwsgi:

uwsgi --socket --protocol=http -w testSite1:app

you should read this page: Test site running under Flask

Next step, configure uwsgi init file in uwsgi.ini in your flask directory:

[uwsgi]chdir = /home/pi/flasktest
module = testSite1:app

master = true
processes = 1
threads = 2

uid = www-data
gid = www-data

socket = /tmp/flasktest.sock
chmod-socket = 664
vacuum = true

die-on-term = true

Create Autostart uWSGI by create new in /etc/systemd/system, called uwsgi.service

Description=uWSGI Service

ExecStart=/usr/local/bin/uwsgi --ini /home/pi/flask/uwsgi.ini


reload the daemon using sudo systemctl daemon-reload and then start the uwsgi service with systemctl:

sudo systemctl start uwsgi.service

configure NGINX to use uWSGI by editing the default site configuration in /etc/nginx/sites-available/default

Delete all content on those file, and replace with this script:

server {
listen 80;
server_name localhost;

location / { try_files $uri @app; }
location @app {
include uwsgi_params;
uwsgi_pass unix:/tmp/flasktest.sock;

Restart NGINX with sudo systemctl restart nginx command.

Test and look your browser.


Post a Comment