Python django.conf.settings.SESSION_ENGINE Examples

The following are 30 code examples for showing how to use django.conf.settings.SESSION_ENGINE(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: models.py    License: 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 2
Project: GTDWeb   Author: lanbing510   File: client.py    License: 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 3
Project: django-useraudit   Author: muccg   File: utils.py    License: 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 4
Project: drf-to-s3   Author: metabolize   File: util.py    License: 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 5
Project: djoser   Author: sunscrapers   File: test_set_password.py    License: 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 6
Project: python   Author: Yeah-Kun   File: client.py    License: 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
Project: python2017   Author: bpgc-cte   File: client.py    License: 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 8
Project: cjworkbench   Author: CJWorkbench   File: main.py    License: 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 9
Project: coursys   Author: sfu-fas   File: testing.py    License: GNU General Public License v3.0 5 votes vote down vote up
def login_user(self, userid):
        """
        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()
        """
        if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
            raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
        try:
            user = User.objects.get(username=userid)
        except User.DoesNotExist:
            user = User(username=userid, password='')
            user.save()
        user.backend = "%s.%s" % ("django.contrib.auth.backends",
                                  "ModelBackend")
        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)

        # 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 10
Project: django-angularjs-blog   Author: bluedazzle   File: test_view_blog.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        classify = Classification.objects.create(c_name='test')
        self.art = Article.objects.create(caption='article',
                                          sub_caption='sub_article',
                                          classification=classify,
                                          content='article test',
                                          publish=True)
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 
Example 11
Project: GTDWeb   Author: lanbing510   File: client.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _session(self):
        """
        Obtains the current session variables.
        """
        if apps.is_installed('django.contrib.sessions'):
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                return engine.SessionStore(cookie.value)
            else:
                s = engine.SessionStore()
                s.save()
                self.cookies[settings.SESSION_COOKIE_NAME] = s.session_key
                return s
        return {} 
Example 12
Project: GTDWeb   Author: lanbing510   File: client.py    License: GNU General Public License v2.0 5 votes vote down vote up
def login(self, **credentials):
        """
        Sets the Factory to appear as if it has successfully logged into a site.

        Returns True if login is possible; False if the provided credentials
        are incorrect, or the user is inactive, or if the sessions framework is
        not available.
        """
        from django.contrib.auth import authenticate, login
        user = authenticate(**credentials)
        if (user and user.is_active and
                apps.is_installed('django.contrib.sessions')):
            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)

            # 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)

            return True
        else:
            return False 
Example 13
Project: GTDWeb   Author: lanbing510   File: middleware.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore 
Example 14
Project: GTDWeb   Author: lanbing510   File: clearsessions.py    License: GNU General Public License v2.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 15
Project: django-qsessions   Author: QueraTeam   File: models.py    License: MIT License 5 votes vote down vote up
def get_session_store_class(cls):
        return import_module(settings.SESSION_ENGINE).SessionStore 
Example 16
Project: django-test-addons   Author: hspandher   File: utils.py    License: MIT License 5 votes vote down vote up
def __init__(self, method = 'GET'):
        super(EnhancedHttpRequest, self).__init__()
        self.method = method

        session_engine = import_module(settings.SESSION_ENGINE)
        self.session = session_engine.SessionStore(session_key = None) 
Example 17
Project: django-test-addons   Author: hspandher   File: utils.py    License: MIT License 5 votes vote down vote up
def create_session(self):
        session_engine = import_module(settings.SESSION_ENGINE)
        store = session_engine.SessionStore()
        store.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 
Example 18
Project: casepro   Author: rapidpro   File: perftest.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _login(self, user):
        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)

        # 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 19
Project: bioforum   Author: reBiocoder   File: client.py    License: MIT License 5 votes vote down vote up
def session(self):
        """Return 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 20
Project: bioforum   Author: reBiocoder   File: client.py    License: 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 21
Project: bioforum   Author: reBiocoder   File: client.py    License: MIT License 5 votes vote down vote up
def logout(self):
        """Log out the user by removing the cookies and session object."""
        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 22
Project: bioforum   Author: reBiocoder   File: middleware.py    License: 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 23
Project: bioforum   Author: reBiocoder   File: clearsessions.py    License: 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 24
Project: django-warrant   Author: MetaMetricsInc   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_request():
    request = HttpRequest()
    engine = import_module(settings.SESSION_ENGINE)
    session = engine.SessionStore()
    session.save()
    request.session = session

    return request 
Example 25
Project: aiohttp-json-rpc   Author: pengutronix   File: django.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, generic_orm_methods=False):
        self.generic_orm_methods = generic_orm_methods
        self.session_engine = import_module(settings.SESSION_ENGINE)

    # Helper methods 
Example 26
Project: pasportaservo   Author: tejoesperanto   File: admin.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        if not change:
            # A new product is added to the list. Should update the flags in the sessions
            # of logged in users, for them to get the update...
            logged_in_users = (
                s for s in Session.objects.exclude(expire_date__lte=timezone.now())
                if s.get_decoded().get('_auth_user_id')
            )
            SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
            flag = 'flag_book_reservation'
            for session_key in (s.session_key for s in logged_in_users if flag in s.get_decoded()):
                s = SessionStore(session_key=session_key)
                del s[flag]
                s.save() 
Example 27
Project: zulip   Author: zulip   File: cache_helpers.py    License: Apache License 2.0 5 votes vote down vote up
def session_cache_items(items_for_remote_cache: Dict[str, str],
                        session: Session) -> None:
    if settings.SESSION_ENGINE != "django.contrib.sessions.backends.cached_db":
        # If we're not using the cached_db session engine, we there
        # will be no store.cache_key attribute, and in any case we
        # don't need to fill the cache, since it won't exist.
        return
    store = session_engine.SessionStore(session_key=session.session_key)
    items_for_remote_cache[store.cache_key] = store.decode(session.session_data) 
Example 28
Project: acacia_main   Author: AcaciaTrading   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = engine.SessionStore(
            ip=request.META.get('REMOTE_ADDR', ''),
            user_agent=request.META.get('HTTP_USER_AGENT', ''),
            session_key=session_key
        ) 
Example 29
Project: notes   Author: forcemain   File: user.py    License: GNU General Public License v3.0 5 votes vote down vote up
def do_clean_user_session(user):
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        for user_session in user.user_sessions.all():
            session.delete(user_session.session_key)
            user_session.delete() 
Example 30
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: client.py    License: MIT License 5 votes vote down vote up
def session(self):
        """Return 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