Chapter 7. Cookies and Sessions

A common pattern in web applications is to maintain the state of an interaction with a particular user/browser by using a cookie stored in the user’s browser that indexes a session on the server. The session is just a place to put data that persists across multiple request/response cycles. Each session has a key that is usually a large random number. The session contains small amounts of data indexed by a key, much like a Python dictionary object. The server stores the session key in a cookie on the user’s browser so that the server can “find” the correct session in the server when it receives the next request from the browser.

HTTP Cookies

Cookies are part of the HTTP request/response cycle. When the server returns a page to the browser, it can include one or more cookies with the page. The web browser then retains those cookies (indexed by the domain name of the website). When a new GET or POST request is sent back to the server, the browser appends all the cookies for the domain name to the request and sends the cookies back to the server on every request, as shown in Figure 7-1. For more information, please also see http://en.wikipedia.org/wiki/HTTP_cookie.

Browser cookie lifecycle
Figure 7-1. Browser cookie lifecycle

The content and names of the cookies are opaque to the browser. The browser keeps the cookies separate for each of the hosts that it is communicating with. In ...

Get Using Google App Engine now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.