Background Image
Table of Contents Table of Contents
Previous Page  311 / 478 Next Page
Information
Show Menu
Previous Page 311 / 478 Next Page
Page Background

Figure 16-1. Examining the session cookie in the Debug toolbar

These session cookies are set for all visitors to a Django site, whether they’re logged in

or not.

When we want to recognise a client as being a logged-in and authenticated user, again,

rather asking the client to send their username and password with every single request,

the server can actually just mark that client’s session as being an authenticated session,

and associate it with a user ID in its database.

A session is a dictionary-like data structure, and the user ID is stored under the key

given by

django.contrib.auth.SESSION_KEY

. You can check this out in a

manage.py

console if you like:

$

python3 manage.py shell

[...]

In [1]: from django.contrib.sessions.models import Session

# substitute your session id from your browser cookie here

In [2]: session = Session.objects.get(

session_key="8u0pygdy9blo696g3n4o078ygt6l8y0y"

)

In [3]: print(session.get_decoded())

{'_auth_user_id':

' harry@mockmyid.com '

, '_auth_user_backend':

'accounts.authentication.PersonaAuthenticationBackend'}

You can also store any other information you like on a user’s session, as a way of tem‐

porarily keeping track of some state. This works for non-logged-in users too. Just use

Mocking in Python

|

283