Cookies are frequently used in web applications to store data in browsers. The most frequent use case is user identification.
We are going to implement a very simple and insecure identification system based on cookies to show how to use them.
The http.cookies.SimpleCookie
class provides all the facilities required to parse and generate cookies.
- We can rely on it to create a web application endpoint that will set a cookie:
from web_06 import WSGIApplication app = WSGIApplication() import time from http.cookies import SimpleCookie @app.route('/identity') def identity(req, resp): identity = int(time.time()) cookie = SimpleCookie() cookie['identity'] = 'USER: {}'.format(identity) for set_cookie in cookie.values(): resp.headers.add_header('Set-Cookie', set_cookie.OutputString()) return b'Go back to <a href="/">index</a> to check your identity'
- We can use it to create one that will parse the cookie and tell us who the current...