You need to create a simple Python web server, but don’t want to have to run a full web server stack.
Use the bottle Python library to run a pure Python web server that will respond to HTTP requests.
To install bottle, use the following command:
sudo apt-get install python-bottle |
The following Python program (called bottle_test in the book resources) simply serves up a message displaying what time the Pi thinks it is. Figure 7-1 shows the page you see if you connect to the Raspberry Pi from a browser anywhere on your network:
from bottle import route, run, template from datetime import datetime @route(‘/’) def index(name=’time’): dt = datetime.now() time = “{:%Y-%m-%d %H:%M:%S}”.format(dt) return template(‘<b>Pi thinks the date/time is: {{t}}</b>’, t=time) run(host=’192.168.1.16′, port=80) |
To start the program, you need to run it with superuser privileges:
$ sudo python bottle_test.py |
This example requires a little explanation.
After the import commands, the @route command links the URL path / with the handler function that follows it.
That handler function formats the date and time and then returns a string of the HTML to be rendered by the browser. In this case, it uses a template into which values can be substituted.
The final run line actually starts the web serving process. Note that you need to specify the hostname and port. Port 80 is the default port for web serving, so if you wish to use a different port, then you need to add the port number with a : after the server address.
Discussion
You can define as many routes and handlers as you like within the program.
bottle is perfect for a small, simple web server projects, and because it’s written in Python, it’s very easy to write a handler function to control hardware in response to the user interacting with the page in a browser.
See Also
For more information, see the bottle project documentation.
For more on formatting dates and times in Python, see Recipe 7.2.