HTTP, which stands for Hypertext Transfer Protocol, is the fundamental protocol used for communication on the web. It is designed to be stateless, meaning that each request from a client (like a web browser) to a server is processed independently, with no memory of prior interactions. Once a request is processed, the server retains no state (or memory) of that request.
That's where Django's session system comes into play.
We left off on how to handle static files in Django, now let's move on to the session.
What is a Session in Django and Why is it Necessary
In typical server-based applications (like those built with Django), a new session is started when a user (or more specifically, a user's browser) first interacts with the application. A session is a way to store data for that particular user's interaction with the server.
A session is a mechanism that allows you to associate data with a user across multiple requests.
When a user visits the web for the first time, Django creates a new session and sends the browser a cookie with a unique identifier, the famous sessionid.
That cookie acts as a bridge between the client and the server: every time the user makes a new request, the browser sends the sessionid and Django can retrieve the previously stored data.
When a session is created, the server sends a small piece of data called a "session cookie" to the user's browser. This cookie contains a unique identifier called the "session ID". This ID is what the server uses to recognize and differentiate between different users (or more accurately, different browser sessions).
The session cookie is stored on the user's browser and sent back to the server with every subsequent request, allowing the server to maintain a consistent session across multiple requests from the same browser.
Middleware components run in order during the request and response phases. When a request arrives, the session middleware grabs the session ID from the client's cookie (if present) and retrieves the associated session data from the configured session engine (database, file, cache, etc.). It then makes this data available as request.session during view processing.
How Django Manages Sessions Internally
The core of this process is the SessionMiddleware, which is responsible for intercepting every request and response:
- It takes the sessionid from the client's cookie (if it exists).
- It retrieves the associated data from the configured session engine (database, file, cache, etc.).
- It makes the data accessible on the request.session object.
- Finally, it saves the changes before sending the response.
This flow allows Django to handle user data without the need to write manual code to identify the user or maintain their state.
Sessions are usually used for user authentication; sessions are the invisible "glue" that maintains coherence between pages, forms, and users.
Basic Session Middleware Configuration in settings.py
Session middleware comes activated by default in most Django projects, but it's worth checking:
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
]After migration, Django creates a table in the database for sessions.
In Django, every user request to the server is encapsulated in a request object. This object includes an attribute called request.session. It functions similarly to a Python dictionary, allowing us to store, retrieve, and manage data using key-value pairs.
For demonstration purposes, I created a new application (session cookie) in the project.
Using request.session in a Django View
Here, I have created a view that essentially counts the number of times a user visits the URL.
# views.py (Variante 1: Uso de render y acceso directo a la sesi贸n)
from django.shortcuts import render
from django.views.decorators.cache import never_cache
# NOTA: En este caso, 'render' necesita un template de archivo (por ejemplo, 'visits.html')
# Asumiendo que existe un archivo 'visits.html' con el contenido: <h1>Total visits: {{ n_visits }}</h1>
@never_cache
def sessionvisit_view_variant1(request):
# 1. Obtener y actualizar el contador
current_visits = request.session.get('n_visits', 0)
new_visits = current_visits + 1
# 2. Guardar el nuevo valor en la sesi贸n
request.session['n_visits'] = new_visits
# 3. Usar el atajo 'render' para cargar y responder.
# Aqu铆 pasamos el *nuevo* valor para que se muestre correctamente.
return render(request, 'visits.html', {'n_visits': new_visits})Every time I refresh the page, the count increases.
In the django_session table, I can find the session keys and data.
We can also display the session attributes in the web browser (using the Set-Cookie header). This way, the browser stores this data in cookies and every time it makes a request to the server, this information is transmitted within the cookie header.
session_data is an encoded string (base64). We can decode it.
import base64
import json
session_str = "eyJuX3Zpc2l0cyI6MTR9:1rQVYV:tvm4LNPRtDXalmCcaR3cXeIMgjj3c8BqzwDca0GdK0U"
# Split the string to get the base64 portion
base64_data = session_str.split(":")[0]
# Pad the string if necessary
padded_base64_data = base64_data + '=' * (-len(base64_data) % 4)
# Decode the base64 string
decoded_data = base64.b64decode(padded_base64_data)
# Assuming the decoded data is JSON serialized
deserialized_data = json.loads(decoded_data)
print(deserialized_data)
"""
{'n_visits': 14}
"""Sessions and cookies are key components in managing state and user data in web applications, but they have different purposes and operate in distinct ways.
Storage Location
- Cookies: Stored on the client side, meaning in the user's web browser.
- Sessions: Stored on the server side. The session ID, which is a reference to the server-side data, may be stored in a client-side cookie.
Security
- Cookies: Since they are stored on the client side, cookies are more vulnerable to security threats such as manipulation and eavesdropping. Sensitive data should not be stored directly in cookies.
- Sessions: Generally more secure as the data is stored on the server. Only the session ID is exchanged with the client, reducing the risk of exposing sensitive data.
Size
- Cookies: Limited in size (typically 4 KB). Not suitable for storing large amounts of data.
- Sessions: Can store larger amounts of data as they are not subject to the same size limitations as cookies.
Use Cases
- Cookies: Ideal for storing small pieces of non-sensitive information, such as user preferences or settings.
- Sessions: More suitable for managing user authentication, storing user-specific data during the web session, and handling sensitive data.
Best Practices and Security in Django Sessions
To protect the integrity of sessions, I recommend:
Enabling HTTPS and using SESSION_COOKIE_SECURE = True.
Not storing sensitive information (passwords, tokens).
Using SESSION_EXPIRE_AT_BROWSER_CLOSE if you want the session to end when the browser is closed.
Deleting old sessions with the command:
$ python manage.py clearsessions
In high-traffic environments, using cache-based sessions (django.contrib.sessions.backends.cache) may also be more efficient.
Frequently Asked Questions about Sessions in Django
- Where is session data stored?
- By default, in the django_session table of the database, although you can change the backend to files or cache.
- How to delete a session or log the user out?
- You can use request.session.flush() to delete all data for the current session.
- How to inspect the content of request.session?
- Just print it to the console or in a view:
- print(request.session.items())
Conclusion
Django sessions are a powerful tool for maintaining user state in web applications without compromising security.
Understanding how they are created, stored, and managed allows for building robust authentication systems and lasting customizations.
Mastering request.session was key to understanding the "brain" of Django and its way of connecting data across requests.
Next step, basic use of the Shell - Interactive Python Console in Django
I agree to receive announcements of interest about this Blog.
Learn to master sessions in Django. Discover how to manage user state with `request.session`, the key difference between sessions and cookies, and security best practices for building robust web applications. Includes code examples!