A beginners guide to developing Web Applications on Linux with Python 3 and Flask

A beginners guide to developing  Web Applications on Linux with  Python 3 and Flask

Whether playing on Linux or working on Linux there is a good chance you have come across a program written in python. Back in college I wish they taught us Python instead of Java, it’s fun to learn and useful in building practical applications like the yum package manager.

Flask is a simple Python Web Framework which provides you with the basic requirements your app will need like Routes, Requests, Responses and then gets out of your way. Along with extensions like Flask-Restful and Flask-SQLAlchemy Flask makes it very easy to build Web Apps with Python.

In this tutorial I will take you through how I built a simple application which displays useful information like memory usage per process, CPU percentage etc using Python 3, Subprocess and a micro framework called flask.

Python Basics, Lists, Classes, Functions, Modules.
HTML/CSS (basic)

You don’t have to be an advanced python programmer to follow this tutorial, But before you go further I recommend you read https://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Installing Python 3 on Linux

On most Linux distributions python is installed by default. This is how you can find out the python version on your system.

[leo@linux-vps ~]# python -V
Python 2.7.5

We will be using python version 3.x to build our app. As per Python.org all improvements are now only available in this version which is not backward compatible with python 2.

Caution: Before your proceed I strongly recommend you try this tutorial out on a Virtual machine, since python is a core component of many Linux Distributions any accidents may cause permanent damage to your system.

This step is for RedHat based variants like CentOS (6&7), Debian based variants like Ubuntu,Mint and Rasbian can skip this step as you should have python version 3 installed by default. If not use apt-get instead of yum to install the relevant packages below.

[leo@linux-vps] sudo yum groupinstall 'Development Tools'
[leo@linux-vps] sudo  yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel
[leo@linux-vps] wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
[leo@linux-vps] tar -xvzf Python-3.4.2.tgz
[leo@linux-vps] cd Python-3.4.2
[leo@linux-vps] ./configure
[leo@linux-vps] make
# make altinstall  is recommended as make install can overwrite the current python binary, 
[leo@linux-vps]   make altinstall

After a successful, installation you should be able to access the python 3.4 shell with the command below.

[leo@linux-vps]# python3.4
Python 3.4.2 (default, Dec 12 2014, 08:01:15)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit ()

Installing packages in python with PIP
Python comes with it’s own package manager, similar to yum and apt-get. You will need to use it to download, install and uninstall packages.

[leo@linux-vps] pip3.4 install "packagename"

[leo@linux-vps] pip3.4 list

[leo@linux-vps] pip3.4 uninstall "packagename"

Python Virtual Environment
In Python a virtual environment is a directory where your projects dependencies are installed. This is a good way to segregate projects with different dependencies. It also allows you to install packages without the need for sudo access.

[leo@linux-vps] mkdir python3.4-flask
[leo@linux-vps] cd python3.4-flask 
 [leo@linux-vps python3.4-flask] pyvenv-3.4 venv

To create the virtual environment you will need to use the “pyvenv-3.4” command. This will create a directory called “lib” inside the venv folder where the dependencies for this project will be installed. It will also create a bin folder which will contain pip and python executables for this virtual environment.

Activating the Virtual Environment for our Linux system information project

 [leo@linux-vps python3.4-flask] source venv/bin/activate
 [leo@linux-vps python3.4-flask] which pip3.4
[leo@linux-vps python3.4-flask] which python3.4

Installing flask with PIP
Lets go ahead and install out first module the flask framework which will take care of the routing and template rendering of our app.

 [leo@linux-vps python3.4-flask]pip3.4 install flask

Creating your first app in flask.
Step 1:Create directories where your app will reside.

[leo@linux-vps python3.4-flask] mkdir  app
 [leo@linux-vps python3.4-flask]mkdir app/static
 [leo@linux-vps python3.4-flask]mkdir app/templates

Inside the python3.4-flask folder create a folder called app which will contain two sub-folders “static” and “templates”. Our python script will reside inside the app folder, files like css/js inside the static folder and templates folder will contain our html templates.

Step 2:Create an initialization file inside the app folder.

[leo@linux-vps python3.4-flask] vim app/_init_.py
from flask import Flask

app = Flask(__name__)
from app import index

This file will create a new instance of Flask and load our python program stored in a file called views.py which we will create next.

[leo@linux-vps python3.4-flask]vim app/views.py
from app import app

def index():
 import subprocess
 cmd = subprocess.Popen(['sudo', './ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
 out,error = cmd.communicate()
 memory = out.splitlines()    

Routing in flask is handled by the route decorator. It is used to bind a URL to a function.


In order to run a shell command in python you can use the Popen class from Subprocess module.

subprocess.Popen(['sudo', './ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

This class will take a list as an argument, the first item of the list will default to being executable while the next item will be considered the option. Here is another example

subprocess.Popen(['ls', ‘-l’],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

stdout and stderr will store the output and error of this command respectively. You can then access this output via the communicate method of the Popen class.

out,error = cmd.communicate()

To display the output in a better way via the html template, I have used the splitlines () method,

memory = out.splitlines()

More information on python subprocess module is available in the docs at the end of this tutorial.

Step 3: Create an html template where we can display the output of our command.

In order to do this we need to use the Jinja2 template engine in flask which will do the template rendering for us.

Your final views.py file should look as follows

from flask import render_template
from app import app

def index():
 import subprocess
 cmd = subprocess.Popen(['sudo', './ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) out,error = cmd.communicate() memory = out.splitlines() return render_template('index.html', memory=memory)

Now create an index.html template inside the templates folder, flask will search for templates in this folder.

[leo@linux-vps python3.4-flask]vim app/templates/index.html

Memory usage per process

{% for line in memory %}
    {{ line.decode('utf-8') }} 
   {% endfor %}

The Jinja2 template engine allows you to use the “{{ … }}” delimiter to print results and {% … %} for loops and value assignment. I used the “decode()” method for formatting purposes.

Step 4: Running the app.

[leo@linux-vps python3.4-flask]vim run.py
from app import app
app.debug = True
app.run(host='', port=80)

The above code will run the app in debug mode. If you leave out the IP address and port it will default to localhost:5000.

[leo@linux-vps python3.4-flask] chmod +x run.py
[leo@linux-vps python3.4-flask] python3.4 run.py

how to install python 3 and flask on linux
I have added more code to the app so that it gives you cpu, I/O and load avg as well.
how to install python 3 and flask on linux

You can access the code to this app here.

If you are interested in building Web Applications on Linux with Flask and Python then I recommend you read :

Building a MySQL app with Flask

Building a PostgreSQL app with Flask

Building a Database driven JSON API with Flask

Scaffolding Web Applications on Linux with Flask-Scaffold,

Update : You can also use the psutil package for more indepth information.


Follow me

Leo G

Is a Linux Hobbyist and Enthusiast. He Strongly believes in OpenSource Software and would like you to view and download his software at https://github.com/Leo-g
Follow me

  • Pingback: 1 – Creating Your First App on Linux with Python and Flask – Exploding Ads()

  • Pingback: 1 – Creating Your First App on Linux with Python and Flask – Official Offeryour.com Blog()

  • Pingback: Creating your first Linux App with Python and Flask | Linux Admins()

  • J. Chung

    “Back in college I wish they thought us Python instead of Java like they do today,…”

    Does this mean they’re teaching Python instead of Java these days in college? Or does this mean they taught you Java, and they are still teaching Java. Just need some clarification.

    • lol, Yes python is now the default introductory language, I was taught java, it almost caused a tumor in my brain, maybe bcoz of the way they taught it.

      • Yuri

        Unfortunately still Java and PHP for me. I too wish I was taught Python and given the option to branch out after 🙁

        • I was taught Java at Uni and learnt PHP on my own. I also went onto study C++ later. I find that these languages are fantastic and they make it far easier to learn each other, once you have learnt one of them.

          It would be a shame to be taught Python instead of Java, but great if they taught it in addition. Java is still my programming language of choice for multithreaded applications.

  • Pingback: Creating your First App on Linux with Python and Flask - Techbait Tech News()

  • no reply

    Having people install VM application and install new Linux distros inside their existing Linux system is a bit heavy handed for one small demonstration web app.

    Better suggestion is to have them use virtualenv and perhaps install virtualenvwrapper.sh package and setup a new package and corresponding env with its own dedicated pip so installing python modules does not end up installing in your system python directories keeping them clean and untouched while your project has all of the add on packages/modules you need.

    $ mkproject first-flask-app
    $ pip install your-list-of-packages
    (Work on your project until done)
    (Stop the python virtualenv when done)
    $ deactivate

    (At future time work on project again)
    $ workon first-flask-app

    • Yes I have added that information in my tutorial, but accidents do happen, i know experienced people who completely removed python binary 🙂

      • Yea, that reminds me of the time I accediently deleted my GUI…

        • Leo G

          I have done that too 🙂

  • Pingback: Creating your First App on Linux with Python and Flask | 4an Nyheter()

  • Jose

    Nice tutorial. The only issue I have with this approach to native apps, is how do you kill them? The problem is that the output (the browser) is disconnected from the application. If I close the browser how do I automatically kill the flask app ? I know just closing the terminal will do the trick just looking for something more elegant.

  • Pingback: Links 22/12/2014: GNU/Linux at Sky News, Another Tizen Camera | Techrights()

  • Hi, thanks for this interesting tutorial. I got a problem. I tried all the steps religiously as given in the tutorial. I still get the error message when I run the run.py, “ImportError: No module named ‘flask”.

    The last part of my attempt to install flask gave me this message if it helps. Where did I go wrong?

    Cleaning up...
    Command /usr/bin/python2.7 -c "import setuptools;__file__='/tmp/pip_build_gls/flask/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-lOQHBC-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip_build_gls/flask
    Storing complete log in /home/gls/.pip/pip.log

    • Hey Anand,

      The first error message suggests that flask is not installed, From the 2nd error it seems you are using python 2.7, I have detailed the steps for python 3.4 and I recommend you install and try this tutorial in the same version of python

  • Pingback: How to build CRUD app with Python, Flask, SQLAlchemy and MySQL -()

  • Pingback: Python PostgreSQL example -()

  • Pingback: JSON web token authentication with Flask and Angularjs -()

  • Nik

    Very well Explained.
    got an error , Please help resolving it.

    nik python3.4_flask # python3.4 run.py
    Traceback (most recent call last):
    File “run.py”, line 1, in
    from app import app
    ImportError: cannot import name ‘app’

    • Leo G

      It could be because of your app folder is not in the same folder as run.py. The app folder contains the the code to create a flask app as follows:
      from flask import Flask
      app = Flask(__name__)

      You can also add this code in your run.py file and check

  • Pingback: Buidling a database driven RESTFUL JSON API in Python 3 with Flask Flask-Restful and SQLAlchemy -()

  • jeffrey

    How does Flask have permissions to run ps_mem which needs sudo privileges?
    We are talking about this ps_mem?

    • Leo G

      The User running Flask needs to have sudo permissions, I have made the change to the code, Thanks

  • Pingback: A hitchhikers guide to troubleshooting linux memory usage -()

  • Brad

    Thanks for this great tutorial.
    I ran into this error and now I’m stuck:
    File “/root/python3.4-flask/app/__init__.py”, line 5, in
    from app import index
    ImportError: cannot import name ‘index’

    any suggestions?

  • Pingback: Bookmarks for March 25th through March 26th | Chris's Digital Detritus()