Django: How to set sessionid cookie for AnonymousUser without using SESSION_SAVE_EVERY_REQUEST

I am trying to track AnonymousUsers to find out when they first come to the site, and when they then register on the website.

To do this, I created middleware with the corresponding functionality, but it was initially assumed that each anonymous user already had a session associated with it (i.e. cookie sessionid will be set in the first response, and the connected session is already created in django_session). Note. Session applications and middleware are present.

This does not seem to be the case, since viewing the session middleware when an anonymous user first appears on the site, the session never changes (users do it because '_auth_user_id' and '_auth_user_backend' are installed) and therefore are never created:

SessionMiddleware.process_response

def process_response(self, request, response):
    """
    If request.session was modified, or if the configuration is to save the
    session every time, save the changes and set a session cookie.
    """
    try:
        accessed = request.session.accessed
        modified = request.session.modified
    except AttributeError:
        pass
    else:
        if accessed:
            patch_vary_headers(response, ('Cookie',))
        if modified or settings.SESSION_SAVE_EVERY_REQUEST:
            if request.session.get_expire_at_browser_close():
                max_age = None
                expires = None
            else:
                max_age = request.session.get_expiry_age()
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
            # Save the session data and refresh the client cookie.
            request.session.save()
            response.set_cookie(settings.SESSION_COOKIE_NAME,
                    request.session.session_key, max_age=max_age,
                    expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                    path=settings.SESSION_COOKIE_PATH,
                    secure=settings.SESSION_COOKIE_SECURE or None,
                    httponly=settings.SESSION_COOKIE_HTTPONLY or None)
    return response

Attempt 1

To try to overcome this, in my middleware that sits below the session middleware, I would force save () on the session to create it:

if hasattr(request, 'session') and not request.session.session_key:
    request.session.save()

This will provide session_key, but unfortunately when SessionMiddleware.process_response is called, request.session.modified is still False, so sessionid cookie is not set ...


Attempt 2

, -, , , request.session.modified == True, SessionMiddleware.process_response:

if hasattr(request, 'session') and not request.session.session_key:
    request.session.save()
    request.session['some_variable'] = True

, , , SESSION_SAVE_EVERY_REQUEST, , .


, , SESSION_SAVE_EVERY_REQUEST=True?

!

+5
1

(, ).

session.modified true

if hasattr(request, 'session') and not request.session.session_key:
    request.session.save()
    request.session.modified = True

, docs .

+5

All Articles