14

I want to be able to collect basic stats on the use of a webapp by users, both anonymous and logged-in.

The commonality here would be that using session ids, I could store data for both logged-in and logged-out users, and still be able to link the stored stats to a given session (who the session belongs to is immaterial).

However, I'm running into issues with collecting the session_key, as this does not appear to be set when an anonymous user enters the site (presumably because of the fact Django sessions are only saved when modified.

When I test a view with a logged-in user:

def create(request, *args, **kwargs):
    print request.session.session_key

For a logged in user, the session_key is printed. For a logged out user or anonymous user this is None. On first request to the site, the session does not exist and consequently is not available to the view.

My current plan is to create a custom Middleware as a subclass of the official session middleware, but overriding process_request() to instantiate sessions for those who do not have one via session.save().

My only concern with this approach is that I'm not sure if it will have unforeseen consequences for other parts of Django - do people have any suggestions?

Anton Manevskiy
  • 809
  • 6
  • 14
jvc26
  • 6,363
  • 6
  • 46
  • 75
  • I'd create a new middleware that does just that, for me it seems more robust and less likely to break in the future. – Tiago Sep 08 '15 at 13:10

2 Answers2

11

In a past project I did what you are suggesting but just within a view where I needed to use session_key for unauthenticated visitors. It did not cause any problems in my project:

if not request.session or not request.session.session_key:
   request.session.save()

# request.session.session_key now set
Eric Conner
  • 10,422
  • 6
  • 51
  • 67
-3

You can choose to save session every request by setting:

SESSION_SAVE_EVERY_REQUEST = True

This force django to assign the session key for each session

https://docs.djangoproject.com/en/2.1/topics/http/sessions/#when-sessions-are-saved

Mattia Fantoni
  • 889
  • 11
  • 15