Login

CurrentSessionIDMiddleware

Author:
troolee
Posted:
July 23, 2010
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.