Skip to main content

Python Web Application Server on the RaspberryPi


One of the great features of the Rev. B RaspberryPi is the built-in Ethernet connection, which opens up many possibilities for web-connected projects. This enables this small device to be able to operate as a web server, ideal for running custom web applications. Since the RaspberryPi can also be connected to a host of other sensors and devices through the GPIO ports, this opens up the possibility of creating web-controlled devices.

Choosing a Web Framework

Since Python is the main programming language for controlling the RaspberryPi, I thought that the ideal web server for the device is a Python-based web framework. This means that the code for controlling the RaspberryPi's GPIO could be integrated right into the code for the web server.

There are a number of Python web frameworks available - so that run some heavy-weight Internet websites. However, the ideal solution is a web framework that is:
  • Easy to install
  • Quick to learn
  • Simple to write
  • Fast and lightweight
Even when considering this criteria, there are multiple options. I settled on one that I really like: Flask. The Flask project describes the framework as a microframework that is fun to work with. That sounds like the perfect accompaniment to a RaspberryPi!

Installing Flask on the RaspberryPi

Installing Flask on the RaspberryPi is really straightforward:

 sudo apt-get install python-pip  
 sudo pip install Flask  
 That's it! What we get is a built-in web server, a Python web framework which is WSGI-compliant, and a built-in templating engine (Jinja2 templates).

Hello World Web App

Once you have Flask installed, then you'll be itching to write your first "Hello World!" web app. Just find a suitable location on your RaspberryPi to store your code (I like to use a 'Sites' directory in the home folder and create a sub-directory for each project e.g. ~/Sites/hello), and a hello.py file as follows:

 from flask import Flask  
 app = Flask(__name__)  
 @app.route("/")  
 def hello():  
   return "Hello World!"  
 if __name__ == "__main__":  
   app.run('0.0.0.0')  

If you've checked out the Flask website, you'll recognise this code as their starting example, with one difference: the addition of '0.0.0.0'. This makes sure that the web server is going to listen on all network devices, so you can browse to the web site from anywhere on your local network.

To start the web server just run:
 $ python hello.py   
  * Running on http://0.0.0.0:5000/  

This will start the built-in web server and it will be listening for web requests on port 5000. You can browse to your web site from any computer, tablet or smart phone that is on your local network by navigating to http://the-ip-address-of-your-pi:5000/ e.g. http://192.168.1.105:5000/. There you will be greeted by your glorious, welcoming message.

Adding a Templated Web Page

Generating HTML from Python code quickly becomes unmanageable, so the recommended approach is to use a templating engine. The Flask install includes the Jinja2 templating engine which makes it quick and easy to develop web applications. Flask is configured to look for templates in a directory called templates. So create a folder structure like this:

 /hello  
   hello.py  
   /templates  
     hello.html  


So, let's create the hello.html template:
 <!DOCTYPE HTML>  
 <html>  
 <header>  
   <title>Welcome!</title>  
 </header>  
 <body>  
   <h1>Hello from the RaspberryPi</h1>  
 </body>  
 </html>  

And now change hello.py to use the template. This is done using render_template:
 from flask import Flask  
 from flask import render_template  
   
 app = Flask(__name__)  
   
 @app.route('/')  
 def hello(name=None):  
   return render_template('hello.html')  
     
 if __name__ == "__main__":  
   app.run('0.0.0.0')  

Restart the web server by running python hello.py and visit the RaspberryPi web page to see your new templated, web application.

That's it! You now have the basis for developing web applications that run on the RaspberryPi, written in Python. For more information on Flask, I recommend working through the tutorials on the Flask website. Once you have a better grasp of working with Flask, you'll be ready to add Python code that controls your RaspberryPi directly from your web application. Stay tuned for the next lesson.


Comments

  1. Thank you for this tutorial. After a lot of time trying to find something simple to grasp the basics of Flask, I arrived here.

    Now I can continue to play with my RPi!

    ReplyDelete

Post a Comment

Popular posts from this blog

Web-based IR Remote on the Raspberry Pi

There are many devices that use infrared remote controls - TV's, DVD players, cameras, power sockets. So getting a Raspberry Pi to be able to send remote control signals opens up many possibilities for projects. Combining the GPIO pins with a web server on the Raspberry Pi means that we can create a web UI to control these devices. Installing LIRC on the Raspberry Pi One of the great things about running a Linux operating system on the Raspberry Pi is that it provides access to a wealth of software projects that can run on the device. One of these is the Linux Infrared Remote Control (LIRC) project that provides a way of receiving and transmitting IR signals from many remote controls. LIRC provides a method of recording signals from a remote control and storing them in a configuration file, so that they can be sent directly from the Raspberry Pi. Installing LIRC on the Raspberry Pi needs the latest firmware to be on the Raspberry Pi. One of the clearest guides I've fou

Installing Ubuntu on a Retina Macbook Pro - the easy way

Update : If you have Mac OS X 10.10 (Yosemite) installed, then the rEFInd installation needs to be handled differently. Please check the rEFInd website for more details. In my previous installation guide , I outlined the first way that I found of installing Ubuntu on a Retina Macbook Pro. One of the challenges of the installation was that the boot manager, rEFInd, needed the Linux kernel to be copied from the Linux partition to the Mac OS X partition. This then becomes a painful process that needs to be repeated every time there is a kernel update on Ubuntu. Fortunately, there is a better way! Thanks to a comment on the rEFInd website, I found out that file system drivers can be installed that allow rEFInd to read the Linux partition. This post outlines the full installation instructions, but if you already followed the previous guide, you can update the rEFInd installation and configuration file. I've included some instructions on that in the post. 1. Partition the Hard

Installing Ubuntu on Retina Macbook Pro

There is an update to this post that shows a simpler and more maintainable approach to the installation . Installing Ubuntu on a Mac tends to be a little trickier than installing on a PC as Macs use EFI instead of BIOS. Now, with the introduction of Apple's Retina Macbook Pro screens we have an additional complication. However, Canonical and the Ubuntu community have been investing some time in getting the Retina Macbooks to play nice with Ubuntu 13.04, so I decided to get the latest, bleeding edge version. The great thing is that there has been an effort to keep the trunk version stable, so I've that getting the pre-release version of Ubuntu 13.04 to be a great solution. If you search the Internet for information about running Ubuntu on the Retina Macbook Pro, you'll find tales of issues with the screen resolution (running at 2880x1880 with tiny icons and text), and driver issues with WiFi and sound. Well, I'm pleased to say, that Ubuntu 13.04 (with the 3.8.0-6