Django is a high-level Python Web framework that allows developers to create complex and database-driven websites. One of the fundamental features of Django is the Session framework that allows you to store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies (Source: Django project Documentation).
The core of how to work with sessions lies in the request.session object. Let’s go through an example:
The most direct way to set a session value is to assign to the dictionary using conventional python syntax. If for instance we want to set a value for “fav\_color” to request.session, you would use:
```
def set_fav_color(request):
request.session[‘fav_color’] = ‘blue‘
```
Django will save the value ‘blue’ under the key ‘fav\_color’ for the duration of the session. Django uses a browser cookie to hold a session ID, and the actual data is stored on the server.
To retrieve this value, we can use this:
```
def get_fav_color(request):
fav_color = request.session[‘fav_color’]
print(fav_color)
```
For deleting the value, you can use the del method:
```
def delete_fav_color(request):
del request.session[‘fav_color’]
```
Django sessions are lazy. According to the official Django documentation, “the session dictionary is not evaluated unless it is used” and the “Session is saved only if it has been modified”.
To ensure that the session value has been set, Django provides a number of methods to interact with the session dictionary:
- get(key, default=None): Returns the value of the session key if it exists, or default if it does not exist.
- keys(): Returns a list of all keys in the session.
- items(): Returns a list of all items in the session.
- clear(): Removes all items from the session.
A caveat is that modifying session data within a cycle calls Django to set a session cookie with each response. To avoid this, you can use the “.set_test_cookie()” and “.test_cookie_worked()” methods to test if the user’s browser accepts cookies.
In sum, Django sessions is a powerful tool to handle browser sessions, to maintain the state of the client, and server communication, offering an optimal user experience. For more advanced topics like session expiration, browser-length sessions, secure cookies or Learn more in the Python Web framework, Django official documentation.
Resources used:
- Django Project Documentation (https://docs.djangoproject.com/en/3.1/topics/http/sessions/)
- MDN Web Docs (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions)