Login

CurrentSessionIDMiddleware

Author:
troolee
Posted:
July 23, 2010
Language:
Python
Version:
Not specified
Tags:
middleware session
Score:
0 (after 2 ratings)

The middleware assigns a unique identifier for session. The session id doesn't depend of session or whatever else. It only need cookies to be turned on.

The session id is reassigned after client close a browser. Identifier of the session could be read from request: request.current_session_id.

You can setup name of the cookie in yours settings module (FLASH_SESSION_COOKIE_NAME).

request.current_session_id is lazy. It means the ID will be assigned and cookie will be returned to client after first usage.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from uuid import uuid4

from django.conf import settings


if hasattr(settings, 'FLASH_SESSION_COOKIE_NAME'):
    FLASH_SESSION_COOKIE_NAME = settings.FLASH_SESSION_COOKIE_NAME
else:
    FLASH_SESSION_COOKIE_NAME = 'XFlashSessionID'


class LazySessionId(object):
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_current_session_id'):
            if FLASH_SESSION_COOKIE_NAME in request.COOKIES:
                request._cached_current_session_id = request.COOKIES[FLASH_SESSION_COOKIE_NAME]
            else:
                request._cached_current_session_id = str(uuid4()) 
        return request._cached_current_session_id


class CurrentSessionIDMiddleware(object):
    def process_request(self, request):
        request.__class__.current_session_id = LazySessionId()
        
    
    def process_response(self, request, response):
        if hasattr(request, '_cached_current_session_id'):
            response.set_cookie(FLASH_SESSION_COOKIE_NAME, request.current_session_id)
        return response

More like this

  1. Always have CSRF and Session cookies by andrew 2 weeks, 4 days ago
  2. Sessions and authentication without cookies by danfairs 7 years, 8 months ago
  3. Upload, Progressbar with sessions by revolunet 6 years, 11 months ago
  4. Middleware for using HttpOnly session cookie (including monkey patching for support for Python <2.6) by chrj 5 years, 2 months ago
  5. Add httponly to session cookie by rodolfo.3 5 years, 3 months ago

Comments

Please login first before commenting.