2

On my website, cookies and sessions are required only for authentication in the admin section. For all other urls I don't want to store cookies or run the session middleware, as it creates an unnecessary DB read/write on every http request.

Is there a way to disable the session middleware for selected pages without the authentication middleware complaining about missing session middleware?

BartoNaz
  • 2,743
  • 2
  • 26
  • 42

1 Answers1

3

It creates an unnecessary DB read/write on every http request.

This is not correct. Django only creates a session if you attempt to write something to it - until then no session is created an no session cookie is set. From the documentation:

By default, Django only saves to the session database when the session has been modified.

Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.

(SESSION_SAVE_EVERY_REQUEST defaults to False).

So for the kind of thing you are describing, sessions will never be created for users who don't access the admin, and there will be no database overhead. The only small overhead will be the middleware that checks for a session cookie.

Community
  • 1
  • 1
solarissmoke
  • 30,039
  • 14
  • 71
  • 73
  • I can't see this behaviour. I'm running the site on the development server with django-debug-toolbar. No matter which page I open, I see the following query in the SQL section of django-debug-toolbar: `QUERY = 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", ... FROM "auth_user" WHERE "auth_user"."id" = %s' - PARAMS = ('1',) `. According to your answer, it should only happen for the admin page, or do I misunderstand something? – BartoNaz Jun 08 '16 at 17:59
  • Checking more carefully, I see that this query appears everywhere only after I have logged in in the admin page, which means that my browser is sending the cookie every time. So this is not an issue for other users, but I'm still wondering whether it is possible to completely ignore cookies for certain urls or views? – BartoNaz Jun 08 '16 at 18:12
  • You subclass Django's session middleware and add some logic that checks the URL before calling the parent methods. IMO you're just substituting one piece of (small) overhead for another though. – solarissmoke Jun 09 '16 at 02:57