Flask Web Application + Rasberry Pi Tutorial

Follow along with the source code:

If you want to use the same files as shown in this tutorial you can download them here. If you have any issues or questions throughout the setup please comment below. This tutorial is targeted for a beginner Raspberry Pi user.

0. Make sure your Raspberry Pi has been updated

# 1. Get Update.
sudo apt-get update
sleep 1
 
# 2. Get Upgrade.
sudo apt-get upgrade -y
sleep 1
 
# 3. Update rpi
sudo rpi-update
sleep 1

#4 Optional Reboot
sudo reboot

 

1. Installing Flask

sudo apt-get install python-virtualenv -y
sudo pip install --upgrade pip
sudo pip install Flask

 pip install –upgrade pip

2. Creating Flask App Application Folder + Subdirectories

Assuming that you are in your /home/pi/ directory.

mkdir FlaskApp
cd FlaskApp
mkdir app
mkdir app/static
mkdir app/templates
mkdir tmp
cd app

 

3. Init Script FlaskApp/app/__init__.py

nano __init__.py

# Copy and paste this into your init file

from flask import Flask
app = Flask(__name__)
from app import views

 

4. Creating the app/views.py file
nano views.py

Copy and paste this into your views.py file

from app import app

@app.route('/')
@app.route('/index')
def index():
    return "I hate using Hello World!"

 

5. Creating and starting the server with run.py

cd /home/pi/FlaskApp
nano run.py

Copy and paste this into your run.py file

#!flask/bin/python
from app import app
HOST='192.168.0.13'

# Starting on my server, your ip address may be different.
app.run(host=HOST, debug=True)

Exit the nano editor and run

chmod +x run.py

 

6. Creating your First Template

cd home/pi/FlaskApp/app/templates
nano index.html

Copy and Paste this into index.html, it will be your home page

<html>
    <head>
        <title>{{ title }} - microblog</title>
    </head>
    <body>
        <h1>This is your first Flask Application {{ user.nickname }}, congrats you did a lot. -___-</h1>
    </body>
</html>

 

7. Using index.html with the FlaskApp/app/views.py file

In the app folder, create a views.py file.

cd FlaskApp/app/
nano views.py

Copy and paste this into your views.py file.

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'nickname': 'Michael'}  # Not a real user
    return render_template('index.html',
                           title='Home',
                           user=user)

 

This is what you should have so far: Screen Shot 2015-06-03 at 12.14.39 PM

 

 

8. Running the application

We can now test our application with the files created above. Head to the FlaskApp folder and run:

python run.py

You should then see this:

Screen Shot 2015-06-03 at 12.30.24 PM

Now head to http://192.168.0.13:5000/ in a web browser to see our progress.

9. Adding a app/templates/layout.html file

<html>
  <head>
    {% if title %}
    <title>{{ title }} - Flask Application</title>
    {% else %}
    <title>Flask Application</title>
    {% endif %}


   <strong><link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"></strong> 
  </head>
  <body>
    
      <div id="header" class="header">
        <div id="nav">
        <ul>
          <li><a href="/index">Home</a></li>
          <li><a href="/about">About</a></li>
        </ul>
      </div> <!-- End Nav -->
      </div> <!-- End Header -->

    <div class="container">
        {% block content %}{% endblock %}
    </div>
  </body>
</html>

 

10. Changing our index.html file

This will inherit the layout.html file so we do not have to change it constantly for updating things such as the navigation. This is what my index.html file now looks like:

<!-- extend base layout -->
{% extends "layout.html" %}

{% block content %}
    <h1>Hello, {{ user.nickname }}!</h1>
    {% for post in posts %}
    <p>
      {{ post.author.nickname }} says: <b>{{ post.body }}</b>
    </p>
    {% endfor %}
{% endblock %}

 

11. Add another HTML template page

I am going to create an ‘About’ page. Head to the template folder and create an about.html file.

<!-- extend layout -->
{% extends "layout.html" %}

{% block content %}

	<h1>This is the About Page</h1>
	<p>You can add content manually or create functions to do it for you. We will get into this more later.</p>
	
{% endblock %}

12. Updating our views.py file

Head to the FlaskApp/app/views.py file and update it to this:

from flask import render_template, flash, redirect
from app import app


@app.route('/')
@app.route('/index')
def index():
    user = {'nickname': 'Michael'}
    posts = [
        {
            'author': {'nickname': 'Fred Post 1'},
            'body': 'This is the body of the first post.'
        },
        {
            'author': {'nickname': 'Craig Post 2'},
            'body': 'This is the body of the second post.'
        }
    ]
    return render_template('index.html',
                           title='Home',
                           user=user,
                           posts=posts)



@app.route('/about')
def about():
    return render_template('about.html',
                           title='About')

This allows us to render the about page when it is selected in a web browser.

 

13. Adding some styling

Create three folders in FlaskApp/app/static/ for our styling files

mkdir static/css static/js static/img

nano static/css/style.css

Copying this into our stylesheet…

body
{
	margin:0;
	font-family:'Open Sans',sans-serif;
}

#header
{
	background:#333;
	width:100%;
	display:block;
	padding:0;
	margin:0;
	height:50px;
	border-bottom:#252525 2px solid
}

h1,p,a
{
	text-align:left;
	text-decoration:none;
	font-weight:300
}

#nav
{
	padding-top:15px;
	text-align:center;
	margin:0 auto;
	font-size:14px;
	font-weight:500
}

#nav ul
{
	margin:0;
	padding:0;
	list-style-type:none;
	list-style-image:none
}

#nav li
{
	margin-right:0;
	display:inline
}

#nav ul li a
{
	text-decoration:none;
	margin:0;
	padding:10px 15px 0;
	color:gray
}

#nav ul li a:hover
{
	color:#ccc;
	text-decoration:none
}

#nav li.current-menu-item a
{
	color:#fff;
	text-decoration:none
}

#nav li.current_page_item
{
	color:#fff;
	text-decoration:none
}

#top
{
	background:#3498db;
	width:100%;
	min-height:100%;
	max-height:100%;
	height:373px;
	padding:90px 20px 10px;
	margin:0 auto;
	text-align:center;
	border-bottom:#2980b9 10px solid;
	color:#fff
}

Try running the Flask Application server again (http://192.168.0.13) to see what changes have been made. Use this to run start the server:

cd /home/pi/FlaskApp
python run.py

You should be able to see this:

Screen Shot 2015-06-03 at 1.38.09 PM

Be sure to post any comments or questions below!



You may also like...

4 Responses

  1. Rob says:

    Hi there,

    Thanks for the great post – helped me set up a Flask App in zero seconds flat. Just wondering if you could recommend a tutorial on the next steps of setting up something useful? Like instead of blog posts, maybe setting up some way of running back-end scripts etc. through a web page using Flask?

    Cheers,
    Rob

    • Michael says:

      Thanks! I am currently working on an application to run some back end scripts. Once I have mine working I will upload a new tutorial. Mine is a SoundCloud downloading application – not sure what I’ll do for the tutorial yet though. If you have any ideas let me know.

  2. nk says:

    You are a good good man Michael! an up to date…COLOURFUL..easy to read blog post. Big wow and bigger Thanks!

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.