Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django sessions for anonymous users

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?

like image 384
jvc26 Avatar asked Sep 08 '15 13:09

jvc26


1 Answers

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
like image 155
Eric Conner Avatar answered Oct 12 '22 05:10

Eric Conner