Question 7.16: You need to create a simple Python web server, but don’t wan......

You need to create a simple Python web server, but don’t want to have to run a full web server stack.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

7.1

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...