Operation Manual
Human-computer interfacing
122
Notes:
hello-web.py:
from webob import Request, Response
class WebApp(object):
def __call__(self, environ, start_response):
# capture the request (input)
req = Request(environ)
# get the name variable,
# default value of 'World' if it is not set
name = req.params.get('name', 'World')
# generate the HTML for the response (output)
html = """
<p>Hello%s!</p>
<formmethod="post">
Enteryourname:<inputtype="text"name="name">
<inputtype="submit"value="SubmitForm">
</form>
"""
# create and return the response
resp = Response(html % name)
return resp(environ, start_response)
application = WebApp()
# main program - the web server
if __name__ == '__main__':
from wsgiref.simple_server import make_server
port = 8080
httpd = make_server('', port, application)
print('Serving HTTP on port %s...'%port)
httpd.serve_forever()
Run this application in IDLE, then launch a web browser. Go to the URL
“http://localhost:8080”. If you’re working from another computer available on the
same network, change “localhost” to the IP address of your Raspberry Pi.
Remember, you can find your IP address by typing “ifconfig” into the Terminal.
You can stop the server by pressing Ctrl-C.
Note that most web pages are normally served on port 80. In order to run on
a port below 1024, your program must be run with “superuser” (root) privileges.
We have used port 8080 with this program – this is commonly used by web
applications that are run as a normal user.
How does it work? The “name” variable is passed through to your program in the
form of a “POST” request. This is generated using a form in HTML. The first time
your page is viewed, the “name” variable is not set, so a default value of “World”
is used.