Operation Manual

Human-computer interfacing
123
Notes:
Cookies
We have just seen an example using a simple form. You may have noticed a
drawback – the “name” variable from that form only lasts for the lifetime of one
request, then it is lost. If we want a variable to remain between requests, we have
to use another type of variable called a “cookie. The program below is a modified
version of the program above that demonstrates how to use cookies.
cookies.py:
from webob import Request, Response
class WebApp(object):
def __call__(self, environ, start_response):
# capture the request (input)
req = Request(environ)
# get the cookiechange variable,
# default value is an empty string
cookiechange = req.params.get('cookiechange', '')
if len(cookiechange.strip())>0:
#changethevalueofcookieifcookiechangebox
# has been completed
cookie = cookiechange
else:
# get the cookie, default value is an empty string
cookie = req.cookies.get('cookie', '')
# generate the HTML for the response (output)
html = """
<p>Thecookieissetto'%s'</p>
<formmethod="post">
Changecookievalue:<inputtype="text"name="cookiechange">
<inputtype="submit">
</form>
"""
# create the response variable
resp = Response(html % cookie)
# store the cookie as part of the response,
#maxage30days(=60*60*24*30seconds)
resp.set_cookie('cookie',cookie,max_age=60*60*24*30)
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()