- 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
- Browser-native date input field by kytta 4 weeks, 1 day ago
- Generate and render HTML Table by LLyaudet 1 month, 1 week ago
- My firs Snippets by GutemaG 1 month, 1 week ago
- FileField having auto upload_to path by junaidmgithub 2 months, 2 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 2 months, 3 weeks ago
Comments
Please login first before commenting.