Python django.conf.settings.SESSION_COOKIE_AGE Examples

The following are 30 code examples for showing how to use django.conf.settings.SESSION_COOKIE_AGE(). 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: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds 
Example 2
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        if not expiry:   # Checks both None and 0 cases
            expiry = settings.SESSION_COOKIE_AGE
        return modification + timedelta(seconds=expiry) 
Example 3
Project: bioforum   Author: reBiocoder   File: signed_cookies.py    License: MIT License 6 votes vote down vote up
def load(self):
        """
        Load the data from the key itself instead of fetching from some
        external data store. Opposite of _get_session_key(), raise BadSignature
        if signature fails.
        """
        try:
            return signing.loads(
                self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies',
            )
        except Exception:
            # BadSignature, ValueError, or unpickling exceptions. If any of
            # these happen, reset the session.
            self.create()
        return {} 
Example 4
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds 
Example 5
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        if not expiry:   # Checks both None and 0 cases
            expiry = settings.SESSION_COOKIE_AGE
        return modification + timedelta(seconds=expiry) 
Example 6
Project: django-expiry   Author: ramonsaraiva   File: middleware.py    License: MIT License 6 votes vote down vote up
def process_response(self, request, response):
        """
        If the current session is fresh (was just created by the default
        session middleware, setting its expiry to `SESSION_COOKIE_AGE`)
        or the session is configured to keep alive, processes all rules
        to identify what `expiry` should be set.
        """
        if not (hasattr(request, 'user') and hasattr(request, 'session')):
            return response

        key = get_settings_key(request.user)

        fresh_session = (
            request.session.get_expiry_age() == settings.SESSION_COOKIE_AGE
        )
        keep_alive = getattr(
            settings, 'EXPIRY_{}_KEEP_ALIVE'.format(key), False
        )

        if fresh_session or keep_alive:
            process_rules(request=request, user=request.user)

        return response 
Example 7
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: signed_cookies.py    License: MIT License 6 votes vote down vote up
def load(self):
        """
        Load the data from the key itself instead of fetching from some
        external data store. Opposite of _get_session_key(), raise BadSignature
        if signature fails.
        """
        try:
            return signing.loads(
                self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies',
            )
        except Exception:
            # BadSignature, ValueError, or unpickling exceptions. If any of
            # these happen, reset the session.
            self.create()
        return {} 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds 
Example 9
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        expiry = expiry or settings.SESSION_COOKIE_AGE   # Checks both None and 0 cases
        return modification + timedelta(seconds=expiry) 
Example 10
Project: openhgsenti   Author: drexly   File: signed_cookies.py    License: Apache License 2.0 6 votes vote down vote up
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except Exception:
            # BadSignature, ValueError, or unpickling exceptions. If any of
            # these happen, reset the session.
            self.create()
        return {} 
Example 11
Project: openhgsenti   Author: drexly   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds 
Example 12
Project: openhgsenti   Author: drexly   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        if not expiry:   # Checks both None and 0 cases
            expiry = settings.SESSION_COOKIE_AGE
        return modification + timedelta(seconds=expiry) 
Example 13
Project: python2017   Author: bpgc-cte   File: signed_cookies.py    License: MIT License 6 votes vote down vote up
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(
                self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies',
            )
        except Exception:
            # BadSignature, ValueError, or unpickling exceptions. If any of
            # these happen, reset the session.
            self.create()
        return {} 
Example 14
Project: python2017   Author: bpgc-cte   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds 
Example 15
Project: python2017   Author: bpgc-cte   File: base.py    License: MIT License 6 votes vote down vote up
def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        if not expiry:   # Checks both None and 0 cases
            expiry = settings.SESSION_COOKIE_AGE
        return modification + timedelta(seconds=expiry) 
Example 16
Project: feedsubs   Author: NicolasLM   File: tasks.py    License: MIT License 6 votes vote down vote up
def synchronize_all_feeds():
    """Synchronize feeds every 30 minutes.

    To avoid a spike of load, the synchronization is spread over the whole
    period.

    Feeds that have their sync explicitly disabled or that have no active
    subscribers are not synchronized.
    """
    current_date = now()
    inactive_user_threshold = current_date - (timedelta(seconds=settings.SESSION_COOKIE_AGE) * 2)
    feeds_to_sync = models.Feed.objects.filter(
        is_sync_enabled=True,
        subscribers__user__is_active=True,
        subscribers__user__last_login__gte=inactive_user_threshold
    )

    ats = list()
    for i in range(0, 29):
        ats.append(current_date + timedelta(minutes=i))

    batch = Batch()
    for feed_id in feeds_to_sync.values_list('id', flat=True):
        batch.schedule_at('synchronize_feed', random.choice(ats), feed_id)
    tasks.schedule_batch(batch) 
Example 17
Project: browserscope   Author: elsigh   File: datastore.py    License: Apache License 2.0 5 votes vote down vote up
def save(self):
        '''Saves the session data to the datastore.'''
        time_till_expire = timedelta(seconds=settings.SESSION_COOKIE_AGE)
        expire_date = datetime.now() + time_till_expire
        
        if self._datastore_session:
            self._datastore_session.session_data = self.encode(self._session)
        else:
            self._datastore_session = Session(session_key=self.session_key, session_data=self.encode(self._session), expire_date=expire_date)
        self._datastore_session.put() 
Example 18
Project: GTDWeb   Author: lanbing510   File: signed_cookies.py    License: GNU General Public License v2.0 5 votes vote down vote up
def load(self):
        """
        We load the data from the key itself instead of fetching from
        some external data store. Opposite of _get_session_key(),
        raises BadSignature if signature fails.
        """
        try:
            return signing.loads(self.session_key,
                serializer=self.serializer,
                # This doesn't handle non-default expiry dates, see #19201
                max_age=settings.SESSION_COOKIE_AGE,
                salt='django.contrib.sessions.backends.signed_cookies')
        except (signing.BadSignature, ValueError):
            self.create()
        return {} 
Example 19
Project: bioforum   Author: reBiocoder   File: file.py    License: MIT License 5 votes vote down vote up
def _expiry_date(self, session_data):
        """
        Return the expiry time of the file storing the session's content.
        """
        expiry = session_data.get('_session_expiry')
        if not expiry:
            expiry = self._last_modification() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)
        return expiry 
Example 20
def test_default_expiry(self):
        # A normal session has a max age equal to settings
        self.assertEqual(
            self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE
        )

        # So does a custom session with an idle expiration time of 0 (but it'll
        # expire at browser close)
        self.session.set_expiry(0)
        self.assertEqual(
            self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE
        ) 
Example 21
def test_custom_expiry_reset(self):
        self.session.set_expiry(None)
        self.session.set_expiry(10)
        self.session.set_expiry(None)
        self.assertEqual(
            self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE
        ) 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: file.py    License: MIT License 5 votes vote down vote up
def _expiry_date(self, session_data):
        """
        Return the expiry time of the file storing the session's content.
        """
        return session_data.get('_session_expiry') or (
            self._last_modification() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)
        ) 
Example 23
Project: python2017   Author: bpgc-cte   File: file.py    License: MIT License 5 votes vote down vote up
def _expiry_date(self, session_data):
        """
        Return the expiry time of the file storing the session's content.
        """
        expiry = session_data.get('_session_expiry')
        if not expiry:
            expiry = self._last_modification() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)
        return expiry 
Example 24
Project: django-session-timeout   Author: labd   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if not hasattr(request, "session") or request.session.is_empty():
            return

        init_time = request.session.setdefault(SESSION_TIMEOUT_KEY, time.time())

        expire_seconds = getattr(
            settings, "SESSION_EXPIRE_SECONDS", settings.SESSION_COOKIE_AGE
        )

        session_is_expired = time.time() - init_time > expire_seconds

        if session_is_expired:
            request.session.flush()
            redirect_url = getattr(settings, "SESSION_TIMEOUT_REDIRECT", None)
            if redirect_url:
                return redirect(redirect_url)
            else:
                return redirect_to_login(next=request.path)

        expire_since_last_activity = getattr(
            settings, "SESSION_EXPIRE_AFTER_LAST_ACTIVITY", False
        )
        grace_period = getattr(
            settings, "SESSION_EXPIRE_AFTER_LAST_ACTIVITY_GRACE_PERIOD", 1
        )

        if expire_since_last_activity and time.time() - init_time > grace_period:
            request.session[SESSION_TIMEOUT_KEY] = time.time() 
Example 25
Project: registration   Author: HackAssistant   File: views.py    License: MIT License 5 votes vote down vote up
def login(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect(reverse('root'))
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = forms.LoginForm(request.POST)
        next_ = request.GET.get('next', '/')
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = auth.authenticate(email=email, password=password)
            if user and user.is_active:
                auth.login(request, user)
                resp = HttpResponseRedirect(next_)
                c_domain = getattr(settings, 'LOGGED_IN_COOKIE_DOMAIN', getattr(settings, 'HACKATHON_DOMAIN', None))
                c_key = getattr(settings, 'LOGGED_IN_COOKIE_KEY', None)
                if c_domain and c_key:
                    try:
                        resp.set_cookie(c_key, 'biene', domain=c_domain, max_age=settings.SESSION_COOKIE_AGE)
                    except:
                        # We don't care if this is not set, we are being cool here!
                        pass
                return resp
            else:
                form.add_error(None, 'Incorrect username or password. Please try again.')

    else:
        form = forms.LoginForm()

    return render(request, 'login.html', {'form': form}) 
Example 26
Project: elearning   Author: delitamakanda   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        if not hasattr(request, 'session') or request.session.is_empty():
            return

        init_time = request.session.setdefault(SESSION_TIMEOUT_KEY, time.time())
        expire_seconds = getattr(
            settings, 'SESSION_EXPIRE_SECONDS', settings.SESSION_COOKIE_AGE)

        session_is_expired = time.time() - init_time > expire_seconds

        if session_is_expired:
            request.session.flush()
            return redirect('/') 
Example 27
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default_expiry(self):
        # A normal session has a max age equal to settings
        self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)

        # So does a custom session with an idle expiration time of 0 (but it'll
        # expire at browser close)
        self.session.set_expiry(0)
        self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) 
Example 28
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_expiry_reset(self):
        self.session.set_expiry(None)
        self.session.set_expiry(10)
        self.session.set_expiry(None)
        self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) 
Example 29
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clearsessions_command(self):
        """
        Test clearsessions command for clearing expired sessions.
        """
        storage_path = self.backend._get_storage_path()
        file_prefix = settings.SESSION_COOKIE_NAME

        def count_sessions():
            return len([
                session_file for session_file in os.listdir(storage_path)
                if session_file.startswith(file_prefix)
            ])

        self.assertEqual(0, count_sessions())

        # One object in the future
        self.session['foo'] = 'bar'
        self.session.set_expiry(3600)
        self.session.save()

        # One object in the past
        other_session = self.backend()
        other_session['foo'] = 'bar'
        other_session.set_expiry(-3600)
        other_session.save()

        # One object in the present without an expiry (should be deleted since
        # its modification time + SESSION_COOKIE_AGE will be in the past when
        # clearsessions runs).
        other_session2 = self.backend()
        other_session2['foo'] = 'bar'
        other_session2.save()

        # Three sessions are in the filesystem before clearsessions...
        self.assertEqual(3, count_sessions())
        management.call_command('clearsessions')
        # ... and two are deleted.
        self.assertEqual(1, count_sessions()) 
Example 30
Project: ontask_b   Author: abelardopardo   File: workflow.py    License: MIT License 4 votes vote down vote up
def lock(
        self,
        session: SessionStore,
        user: get_user_model(),
        update_session: bool = False
    ):
        """Set a session key in the workflow to set is as locked.

        :param session: Session object used for the locking
        :param user: User requesting the lock
        :param update_session: Boolean to flag if a session has to be updated
        :return: The session_key is assigned and saved.
        """
        if session.session_key is not None:
            # Trivial case, the request has a legit session, so use it for
            # the lock.
            self.session_key = session.session_key
            self.save(update_fields=['session_key'])

        # The request has a temporary session (non persistent). This is the
        # case when the API is invoked. There are four possible case:
        #
        # Case 1: The workflow has empty lock information: CREATE SESSION and
        #  UPDATE
        #
        # Case 2: The workflow has a session, but is not in the DB: CREATE
        # SESSION and UPDATE
        #
        # Case 3: The workflow has a session but it has expired: UPDATE THE
        # EXPIRE DATE OF THE SESSION
        #
        # Case 4: The workflow has a perfectly valid session: UPDATE THE
        # EXPIRE DATE OF THE SESSION
        #
        if update_session:
            # Cases 1 and 2. Create a session and store the user_id
            session['_auth_user_id'] = user.id
            session.save()
            self.session_key = session.session_key
            self.save(update_fields=['session_key'])
            return

        # Cases 3 and 4. Update the existing session
        existing_session = Session.objects.get(pk=self.session_key)
        existing_session.expire_date = timezone.now() + datetime.timedelta(
            seconds=settings.SESSION_COOKIE_AGE)
        existing_session.save()