Last active
September 21, 2021 23:15
-
-
Save DrMartiner/ee93bd6fe1af4875f086f8396d13acd8 to your computer and use it in GitHub Desktop.
Create session for anonymous django users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -* | |
from __future__ import unicode_literals | |
import logging | |
from django.conf import settings | |
from importlib import import_module | |
engine = import_module(settings.SESSION_ENGINE) | |
SessionStore = engine.SessionStore | |
logger = logging.getLogger('django.request') | |
class AnonymousSessionMiddleware(object): | |
def process_request(self, request): | |
# type: (request) -> None | |
if not request.user.is_authenticated() and not request.session.session_key: | |
request.session = SessionStore() | |
request.session.create() | |
function_name = settings.get('ANONYMOUS_SESSION_PROCESS_FUNCTION') | |
if function_name: | |
msg = None | |
try: | |
function = __import__(function_name) | |
if callable(function): | |
function() | |
else: | |
msg = '"{}" is not callable'.format(function_name) | |
logger.warn(msg) | |
except ImportError: | |
msg = 'Can not import "{}"'.format(function_name) | |
logger.warn(msg) | |
except Exception as e: | |
msg = 'Error at processing Anonymous request' | |
logger.warn(msg, exc_info=True) | |
def process_anonymous_session(request): | |
# type: (request) -> None | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MIDDLEWARE_CLASSES = [ | |
'django.contrib.sessions.middleware.SessionMiddleware', | |
# ... | |
] | |
ANONYMOUS_SESSION_PROCESS_FUNCTION = 'apps.common.middleware.process_anonymous_session' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment