Raspberry_Pi_Education_Manual

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 # get the cookie, default value is an empty string cookie = req.cookies.get( 'cookie' , '' ) # generate the HTML for the response (output) html = """

The cookie is set to '%s'

Change cookie value:
""" # 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() # create the response variable resp = Response(html % cookie) # has been completed cookie = cookiechange else :

Human-computer interfacing

123

Made with FlippingBook flipbook maker