Ticket #2548: session_middleware.12.diff

File session_middleware.12.diff, 7.6 KB (added by Chris Beaven, 17 years ago)

tests added

  • AUTHORS

     
    229229    Karen Tracey <graybark@bellsouth.net>
    230230    Makoto Tsuyuki <mtsuyuki@gmail.com>
    231231    tt@gurgle.no
    232     Amit Upadhyay
     232    Amit Upadhyay <http://www.amitu.com/blog/>
    233233    Geert Vanderkelen
    234234    viestards.lists@gmail.com
    235235    Milton Waddams
  • django/contrib/sessions/middleware.py

     
    4848    def delete_test_cookie(self):
    4949        del self[TEST_COOKIE_NAME]
    5050
     51    def get_session_age(self):
     52        return self.get('_session_age', settings.SESSION_COOKIE_AGE)
     53    def set_session_age(self, seconds):
     54        " Sets the life of the session, irrespective of global settings. "
     55        if not seconds:
     56            try:
     57                del self['_session_age']
     58            except KeyError:
     59                pass
     60        else:
     61            self['_session_age'] = seconds
     62
     63    def get_expire_at_browser_close(self):
     64        return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE and ('_session_age' not in self)
     65
    5166    def _get_session(self):
    5267        # Lazily loads session from storage.
    5368        self.accessed = True
     
    92107                    obj = Session.objects.get_new_session_object()
    93108                    session_key = obj.session_key
    94109
    95                 if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
    96                     max_age = None
    97                     expires = None
    98                 else:
    99                     max_age = settings.SESSION_COOKIE_AGE
    100                     expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
    101                 new_session = Session.objects.save(session_key, request.session._session,
    102                     datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
    103                 response.set_cookie(settings.SESSION_COOKIE_NAME, session_key,
    104                     max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
     110                session_age = request.session.get_session_age()
     111                delta_age = datetime.timedelta(seconds=session_age)
     112                if request.session.get_expire_at_browser_close():
     113                    session_age = None
     114                    expires = None
     115                else:
     116                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + delta_age, "%a, %d-%b-%Y %H:%M:%S GMT")
     117                Session.objects.save(session_key, request.session._session, datetime.datetime.now() + delta_age)
     118                response.set_cookie(
     119                    settings.SESSION_COOKIE_NAME, session_key,
     120                    max_age=session_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
    105121                    secure=settings.SESSION_COOKIE_SECURE or None)
    106122        return response
  • django/contrib/sessions/tests.py

     
    1010
    1111>>> s.pop('some key', 'does not exist')
    1212'does not exist'
     13
     14########################
     15# session_age settings #
     16########################
     17
     18>>> from django.conf import settings
     19>>> s.get_session_age() == settings.SESSION_COOKIE_AGE
     20True
     21
     22# Custom session age
     23>>> s.set_session_age(10)
     24>>> s.get_session_age()
     2510
     26
     27# Set back to default session age
     28>>> s.set_session_age(0)
     29>>> s.get_session_age() == settings.SESSION_COOKIE_AGE
     30True
     31
     32# Allow to set back to default session age even if no alternate has been set
     33>>> s.set_session_age(0)
     34
     35###############################
     36# get_expire_at_browser_close #
     37###############################
     38
     39# A bit hackish: we're changing the setting then reverting back to
     40# the original setting just in case at the end of these tests.
     41>>> original_setting = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
     42
     43>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
     44
     45# Custom session age
     46>>> s.set_session_age(10)
     47>>> s.get_expire_at_browser_close()
     48False
     49
     50# Default session age
     51>>> s.set_session_age(0)
     52>>> s.get_expire_at_browser_close()
     53False
     54
     55>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
     56
     57# Custom session age
     58>>> s.set_session_age(10)
     59>>> s.get_expire_at_browser_close()
     60False
     61
     62# Default session age
     63>>> s.set_session_age(0)
     64>>> s.get_expire_at_browser_close()
     65True
     66
     67>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_setting
    1368"""
    1469
    1570from django.contrib.sessions.middleware import SessionWrapper
  • docs/sessions.txt

     
    3939It implements the following standard dictionary methods:
    4040
    4141    * ``__getitem__(key)``
     42
    4243      Example: ``fav_color = request.session['fav_color']``
    4344
    4445    * ``__setitem__(key, value)``
     46
    4547      Example: ``request.session['fav_color'] = 'blue'``
    4648
    4749    * ``__delitem__(key)``
     50
    4851      Example: ``del request.session['fav_color']``. This raises ``KeyError``
    4952      if the given ``key`` isn't already in the session.
    5053
    5154    * ``__contains__(key)``
     55
    5256      Example: ``'fav_color' in request.session``
    5357
    5458    * ``get(key, default=None)``
     59
    5560      Example: ``fav_color = request.session.get('fav_color', 'red')``
    5661
    5762    * ``keys()``
    5863
    5964    * ``items()``
    6065
    61 It also has these three methods:
     66It also has these methods:
    6267
    6368    * ``set_test_cookie()``
     69
    6470      Sets a test cookie to determine whether the user's browser supports
    6571      cookies. Due to the way cookies work, you won't be able to test this
    6672      until the user's next page request. See "Setting test cookies" below for
    6773      more information.
    6874
    6975    * ``test_cookie_worked()``
     76
    7077      Returns either ``True`` or ``False``, depending on whether the user's
    7178      browser accepted the test cookie. Due to the way cookies work, you'll
    7279      have to call ``set_test_cookie()`` on a previous, separate page request.
    7380      See "Setting test cookies" below for more information.
    7481
    7582    * ``delete_test_cookie()``
     83
    7684      Deletes the test cookie. Use this to clean up after yourself.
    7785
     86    * ``set_session_age(seconds)``
     87
     88      It takes an integer, number of seconds for which the session should be
     89      valid. This will override the default/global session expiry policy.
     90      See `browser-length sessions vs. persistent sessions`_ for default
     91      session expiry policy. To fall back to the global session expiry policy
     92      again, call ``set_session_age(0)``.
     93
     94    * ``get_session_age()``
     95
     96      Returns the age of the session (which will equal
     97      ``settings.SESSION_COOKIE_AGE`` unless it has been overridden by
     98      ``set_session_age``).
     99
     100    * ``get_expire_at_browser_close()``
     101
     102      Returns either ``True`` or ``False``, depending on whether this session
     103      expires at browser close (which will equal
     104      ``settings.SESSION_EXPIRE_AT_BROWSER_CLOSE`` unless the session age
     105      hase been overridden by ``set_session_age``).
     106
    78107You can edit ``request.session`` at any point in your view. You can edit it
    79108multiple times.
    80109
     
    217246her browser. Use this if you want people to have to log in every time they open
    218247a browser.
    219248
     249These settings are global defaults, and can be overwritten by explicitly calling
     250``request.session.set_session_age()`` as described above in `Using sessions in views`_.
     251
    220252Clearing the session table
    221253==========================
    222254
Back to Top