Python django.conf.settings.SESSION_ENGINE Examples

The following are 30 code examples of django.conf.settings.SESSION_ENGINE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: util.py    From drf-to-s3 with MIT License 6 votes vote down vote up
def establish_session(original_function):
    '''
    Simulate establishing a session.

    Adapted from https://code.djangoproject.com/ticket/10899 and
    http://blog.joshcrompton.com/2012/09/how-to-use-sessions-in-django-unit-tests.html

    FIXME this needs its own tests

    '''
    def new_function(self, *args, **kwargs):
        from importlib import import_module
        from django.conf import settings

        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()  # we need to make load() work, or the cookie is worthless

        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
        self.session_key = store.session_key

        original_function(self, *args, **kwargs)
    return new_function 
Example #2
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def check(cls, **kwargs):
        """
        We use .session_key and CSRF_COOKIE above: check that they will be there, and fail fast if not.
        """
        errors = super().check(**kwargs)

        # Ensure we are using the database session store. (Other SessionStores may also have .session_key?)
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore
        if not issubclass(store, DatabaseSessionStore):
            errors.append(Error(
                "Quiz logging uses request.session.session_key, which likely implies "
                "SESSION_ENGINE = 'django.contrib.sessions.backends.db' in settings."
            ))

        if 'django.middleware.csrf.CsrfViewMiddleware' not in settings.MIDDLEWARE:
            errors.append(Error(
                "CsrfViewMiddleware is not enabled in settings: quiz logging uses CSRF_COOKIE and will fail without "
                "CSRF checking enabled. Also it should be enabled in general."
            ))

        return errors 
Example #3
Source File: test_set_password.py    From djoser with MIT License 6 votes vote down vote up
def test_post_logout_cycle_session(self):
        user = create_user()
        data = {"new_password": "new password", "current_password": "secret"}
        login_user(self.client, user)
        self.client.force_login(user)

        response = self.client.post(self.base_url, data)
        self.assert_status_equal(response, status.HTTP_204_NO_CONTENT)

        user.refresh_from_db()

        session_id = self.client.cookies['sessionid'].coded_value
        engine = importlib.import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore(session_id)
        session_key = session[HASH_SESSION_KEY]

        self.assertEqual(session_key, user.get_session_auth_hash()) 
Example #4
Source File: client.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie() 
Example #5
Source File: client.py    From python2017 with MIT License 6 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie() 
Example #6
Source File: client.py    From python with Apache License 2.0 6 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie() 
Example #7
Source File: main.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete_expired_sessions_and_workflows_forever():
    if settings.SESSION_ENGINE != "django.contrib.sessions.backends.db":
        warnings.warn(
            "WARNING: not deleting anonymous workflows because we do not know "
            "which sessions are expired. Rewrite "
            "delete_expired_sessions_and_workflows() to fix this problem."
        )
        # Run forever
        while True:
            await asyncio.sleep(999999)

    while True:
        try:
            await benchmark(
                logger,
                delete_expired_sessions_and_workflows(),
                "delete_expired_sessions_and_workflows()",
            )
        except:
            logger.exception("Error deleting expired sessions and workflows")
        await asyncio.sleep(ExpiryInterval) 
Example #8
Source File: utils.py    From django-useraudit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def simulate_login(username, password, headers=None):
    rf = RequestFactory()
    request = rf.request(**headers)
    engine = import_module(settings.SESSION_ENGINE)
    request.session = engine.SessionStore()

    # TODO remove when we don't support Django 1.10 anymore
    # request passed in to authenticate only after Django 1.10
    # Also the middleware saving the request to thread local can be dropped
    try:
        user = authenticate(request, username=username, password=password)
    except TypeError:
        middleware.thread_data.request = request
        user = authenticate(username=username, password=password)
    if user:
        login(request, user) 
Example #9
Source File: oj.py    From OnlineJudge with MIT License 5 votes vote down vote up
def get(self, request):
        engine = import_module(settings.SESSION_ENGINE)
        session_store = engine.SessionStore
        current_session = request.session.session_key
        session_keys = request.user.session_keys
        result = []
        modified = False
        for key in session_keys[:]:
            session = session_store(key)
            # session does not exist or is expiry
            if not session._session:
                session_keys.remove(key)
                modified = True
                continue

            s = {}
            if current_session == key:
                s["current_session"] = True
            s["ip"] = session["ip"]
            s["user_agent"] = session["user_agent"]
            s["last_activity"] = datetime2str(session["last_activity"])
            s["session_key"] = key
            result.append(s)
        if modified:
            request.user.save()
        return self.success(result) 
Example #10
Source File: clearsessions.py    From python2017 with MIT License 5 votes vote down vote up
def handle(self, **options):
        engine = import_module(settings.SESSION_ENGINE)
        try:
            engine.SessionStore.clear_expired()
        except NotImplementedError:
            self.stderr.write("Session engine '%s' doesn't support clearing "
                              "expired sessions.\n" % settings.SESSION_ENGINE) 
Example #11
Source File: protocol.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def getSessionEngine(self):
        """Returns the session engine being used by Django.

        Used by the protocol to validate the sessionid.
        """
        return getModule(settings.SESSION_ENGINE).load() 
Example #12
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_login_session_without_hash_session_key(self):
        """
        Session without django.contrib.auth.HASH_SESSION_KEY should login
        without an exception.
        """
        user = User.objects.get(username='testclient')
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        session[SESSION_KEY] = user.id
        session.save()
        original_session_key = session.session_key
        self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key

        self.login()
        self.assertNotEqual(original_session_key, self.client.session.session_key) 
Example #13
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_logout_preserve_language(self):
        """Language stored in session is preserved after logout"""
        # Create a new session with language
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        session[LANGUAGE_SESSION_KEY] = 'pl'
        session.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key

        self.client.get('/logout/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'pl') 
Example #14
Source File: tests.py    From jorvik with GNU General Public License v3.0 5 votes vote down vote up
def _setup_request(self, path, utente, old_request=None):
        request = self.factory.get(path=path)
        if old_request:
            request.session = old_request.session
        else:
            engine = import_module(settings.SESSION_ENGINE)
            request.session = engine.SessionStore()
            request.session.save()
        request.user = utente
        return request 
Example #15
Source File: helpers.py    From avos with Apache License 2.0 5 votes vote down vote up
def setSessionValues(self, **kwargs):
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        for key in kwargs:
            store[key] = kwargs[key]
            self.request.session[key] = kwargs[key]
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 
Example #16
Source File: middleware.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_request(self, request):
        from django.conf import settings
        from django.utils.importlib import import_module
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = engine.SessionStore(session_key) 
Example #17
Source File: test_channels.py    From django-loci with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _force_login(self, user, backend=None):
        engine = importlib.import_module(settings.SESSION_ENGINE)
        request = HttpRequest()
        request.session = engine.SessionStore()
        login(request, user, backend)
        request.session.save
        return request.session 
Example #18
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_logout_preserve_language(self):
        """Language stored in session is preserved after logout"""
        # Create a new session with language
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        session[LANGUAGE_SESSION_KEY] = 'pl'
        session.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key

        self.client.get('/logout/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'pl') 
Example #19
Source File: test_views.py    From devops with MIT License 5 votes vote down vote up
def setup_session(client):
    assert apps.is_installed("django.contrib.sessions"), "sessions not installed"
    engine = import_module(settings.SESSION_ENGINE)
    cookie = client.cookies.get(settings.SESSION_COOKIE_NAME, None)
    if cookie:
        return engine.SessionStore(cookie.value)
    s = engine.SessionStore()
    s.save()
    client.cookies[settings.SESSION_COOKIE_NAME] = s.session_key
    return s 
Example #20
Source File: middleware.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, get_response=None):
        self.get_response = get_response
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore 
Example #21
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def _login(self, user, backend=None):
        from django.contrib.auth import login
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()

        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()
        login(request, user, backend)

        # Save the session values.
        request.session.save()

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data) 
Example #22
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def session(self):
        """
        Obtains the current session variables.
        """
        engine = import_module(settings.SESSION_ENGINE)
        cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
        if cookie:
            return engine.SessionStore(cookie.value)

        session = engine.SessionStore()
        session.save()
        self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
        return session 
Example #23
Source File: utils.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def login_user(self, user):
        """
        Login as specified user, does not depend on auth backend (hopefully)

        This is based on Client.login() with a small hack that does not
        require the call to authenticate()
        """
        user.backend = "django.contrib.auth.backends.ModelBackend"
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()

        request.session = engine.SessionStore()
        login(request, user)

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        # Save the session values.
        request.session.save() 
Example #24
Source File: purge_session_service_tickets.py    From esproxy with MIT License 5 votes vote down vote up
def handle_noargs(self, **options):
        """Purges Session Service Tickets with non-existing session keys."""

        verbose = True if options.get('verbosity') in ['2','3'] else False
        session_engine = __import__(name=settings.SESSION_ENGINE, fromlist=['SessionStore'])
        SessionStore = getattr(session_engine, 'SessionStore')
        s = SessionStore()
        for sst in SessionServiceTicket.objects.all():
            if not s.exists(sst.session_key):
                if verbose:
                    print "deleting session service ticket for session: " + sst.session_key
                sst.delete() 
Example #25
Source File: models.py    From esproxy with MIT License 5 votes vote down vote up
def get_session(self):
        """ Searches the session in store and returns it """
        session_engine = __import__(name=settings.SESSION_ENGINE, fromlist=['SessionStore'])
        SessionStore = getattr(session_engine, 'SessionStore')
        return SessionStore(session_key=self.session_key) 
Example #26
Source File: test_views.py    From troupon with MIT License 5 votes vote down vote up
def test_merchant_can_create_deal(self):

        deal = set_advertiser_and_category()
        request = self.factory.post(
            reverse('merchant_create_deal'), deal)
        request.user = self.user
        engine = import_module(settings.SESSION_ENGINE)
        session_key = None
        request.session = engine.SessionStore(session_key)
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        response = CreateDealView.as_view()(request)
        self.assertEquals(response.status_code, 302) 
Example #27
Source File: test_view.py    From troupon with MIT License 5 votes vote down vote up
def test_confirmation_page_can_be_viewed_by_merchant(self):

        request = self.factory.get(
            reverse('account_merchant_confirm'))
        request.user = self.user
        engine = import_module(settings.SESSION_ENGINE)
        session_key = None
        request.session = engine.SessionStore(session_key)
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        response = MerchantConfirmView.as_view()(request)
        self.assertEquals(response.status_code, 200) 
Example #28
Source File: test_view.py    From troupon with MIT License 5 votes vote down vote up
def test_confirmation_page_cannot_be_viewed_by_user(self):

        request = self.factory.get(
            reverse('account_merchant_confirm'))
        request.user = self.user
        engine = import_module(settings.SESSION_ENGINE)
        session_key = None
        request.session = engine.SessionStore(session_key)
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        response = MerchantConfirmView.as_view()(request)
        self.assertEquals(response.status_code, 302) 
Example #29
Source File: clearsessions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def handle(self, **options):
        engine = import_module(settings.SESSION_ENGINE)
        try:
            engine.SessionStore.clear_expired()
        except NotImplementedError:
            self.stderr.write("Session engine '%s' doesn't support clearing "
                              "expired sessions.\n" % settings.SESSION_ENGINE) 
Example #30
Source File: middleware.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore