from __future__ import absolute_import
from random import random
import logging

from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import request_started

logger = logging.getLogger(__name__)


def clear_expired_sessions(sender, **kwargs):
    """
    Triggered by the request_started signal, this function calls the
    clear_expired method on the session backend, with a certain probability
    (similar to how PHP clears sessions)
    """
    if random() <= clear_expired_sessions.probability:
        try:
            clear_expired_sessions.engine.SessionStore.clear_expired()
            logger.debug('Sessions cleared')
        except NotImplementedError:
            logger.debug('Session engine "%s" does ont support clearing expired sessions.' % settings.SESSION_ENGINE)


def patch_sessions(num_requests):
    """
    Connects the clear_expired_sessions function to the request_started signal,
    and does a little configuration calculations and checking.
    """

    if num_requests < 1:
        raise ImproperlyConfigured('The num_requests setting must be > 0')

    clear_expired_sessions.engine = import_module(settings.SESSION_ENGINE)
    clear_expired_sessions.probability = 1.0 / num_requests
    request_started.connect(clear_expired_sessions)

@@ -78,41 +78,128 @@
 ng%0A%0A
-from django.conf import settings%0A
+try:%0A    # Python %3E= 2.7%0A    import importlib%0Aexcept ImportError:%0A    # Python %3C 2.7; will be removed in Django 1.9%0A    
 from
@@ -215,39 +215,59 @@
 tils
-.
+ 
 import
-lib
  import
- import_module
+lib%0A%0Afrom django.conf import settings
 %0Afro
@@ -1326,16 +1326,26 @@
 ngine = 
+importlib.
 import_m

Make importlib import compatible w/ Django>=1.8