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.
Now add the following content to hello.py
from flask import Flask, render_template,redirect,request,url_for,send_from_directory
@app.route("/",methods=['GET']) # catch the get request and serve the index.html page
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
Now we will write a simple HTML page that will just displays “Hello World”
<title>Python web server</title>
Now we are ready to see our first web page served by Pi.
start the python script
sudo python hello.py
you will see some thing like this if the server started successfully.
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