Setting Up Python web server for Raspberry pi

Pi based HTTP server layout

Pi HTTP Server

Serving web pages from embedded devices is not easy task as embedded devices have limitations in processing power , memory available etc. But with Raspberry Pi this task becomes very easy. We have lot of packages, programming platforms and libraries to chose from because pi is from Linux family.  In this post I am going to show how to setup Pi to server web pages.  I am going to use python to serve web pages. Once we have initial setup running , we can even expose this web services to the internet using ngrok or yaler (if your behind the firewall , you web services will work only in LAN).

python will be already installed in your Pi, so the next step is to install flask. you may get some warnings you can safely ignore them.flask is a simple framework ,you can use for developing web apss. you can learn more about flask here (second and third steps are optional)


sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install python-dev libevent-dev
sudo apt-get install python-pip
sudo pip install flask

Now we will see how to serve static HTML files using flask.

First we need to create python script that will server the requested from clients. I am creating a hello.py file.


mkdir ~/pyServer

cd ~/pyServer

touch hello.py

Now add the following content to hello.py


from flask import Flask, render_template,redirect,request,url_for,send_from_directory
app = Flask(__name__,static_folder='static') # you can place all your static content like javascript,css and images in static folder.

@app.route("/",methods=['GET']) # catch the get request and serve the index.html page
def doGet():
 return render_template('index.html');

if __name__ == "__main__":
 app.run(host='0.0.0.0', port=80, debug=True)

All the HTML files will go into a templates folder in side your project folder(pyServer)

mkdir templates static
cd templates
touch index.html

In static folder you will place all your static content like JavaScript, css and imges if any. Now we are not placing any thing in this directory as we don’t have any static content.

Now we will write a simple HTML page that will just displays “Hello World”

<html>
 <head>
   <title>Python web server</title>
 </head>

 <body>
   <h1>Hello World</h1>
 </body>
</html>

Now we are ready to see our first web page served by Pi.
start the python script

cd ~/pyServer
sudo python hello.py

you will see some thing like this if the server started successfully.

flask server

flask server

we need run this script with sudo as it needs to open the 80 port otherwise it will fail. now open your browser and type in your Pi IP address.

hello world web page served by Pi

hello world web page

Here we have seen how to serve static HTML from Pi, next we will see how to serve dynamic web pages and how to use JavaScript etc.

Add a Comment

Your email address will not be published. Required fields are marked *