What You'll Learn in This Hour |
|
In the past couple of hours, we have covered implementing users and authentication. Now it is time to discuss implementing a session framework that will allow you to provide a persistent state for user data.
As a user browses the website and does various activities, you may want to retain certain data about that user's activities. Generally this is accomplished by setting cookies in the web browser. Storing data in cookies has definite advantages and disadvantages.
Django provides a session framework that abstracts cookies and provides a better form of persistent session data.
The following sections discuss Django's session framework and how to configure the session manager. They also cover using the session manager to add and retrieve data about the session. In addition, we will cover using the HttpRequest object to set and retrieve cookies from the browser.
A cookie is simply a piece of data stored on the user's computer by the web browser. The biggest problem with cookies is that they are not secure. The data in the cookie can be modified by the user, an application, or another website. Another problem with cookies is that users can set their browsers to reject cookies, effectively disabling any control you might try to provide using cookies. Cookies are also only sent to the server when a request is made on the same domain that the cookie was created on. Therefore, cookies cannot be accessed across multiple domains.
The Django session framework solves some of the problems with cookies by storing only a hashed session ID on the browser side and the actual user data on the server side. The session framework allows you to store and retrieve data about a specific site user. The session data is stored in a table in the database by default.