Django

Code

Changeset 7586

Show
Ignore:
Timestamp:
06/07/08 15:28:06 (3 months ago)
Author:
jacob
Message:

Fixed #2548: added get/set_expiry methods to session objects. Thanks, Amit Upadhyay and SmileyChris?.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/AUTHORS

    r7583 r7586  
    361361    tt@gurgle.no 
    362362    David Tulig <david.tulig@gmail.com> 
    363     Amit Upadhyay 
     363    Amit Upadhyay <http://www.amitu.com/blog/> 
    364364    Geert Vanderkelen 
    365365    I.S. van Oostveen <v.oostveen@idca.nl> 
  • django/trunk/django/conf/global_settings.py

    r7537 r7586  
    290290SESSION_COOKIE_PATH = '/'                               # The path of the session cookie. 
    291291SESSION_SAVE_EVERY_REQUEST = False                      # Whether to save the session data on every request. 
    292 SESSION_EXPIRE_AT_BROWSER_CLOSE = False                 # Whether sessions expire when a user closes his browser. 
     292SESSION_EXPIRE_AT_BROWSER_CLOSE = False                 # Whether a user's session cookie expires when they close their browser. 
    293293SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # The module to store session data 
    294294SESSION_FILE_PATH = None                                # Directory to store session files if using the file session module. If None, the backend will use a sensible default. 
  • django/trunk/django/contrib/sessions/backends/base.py

    r7294 r7586  
    55import sys 
    66import time 
     7from datetime import datetime, timedelta 
    78from django.conf import settings 
    89from django.core.exceptions import SuspiciousOperation 
     
    129130    _session = property(_get_session) 
    130131 
     132    def get_expiry_age(self): 
     133        """Get the number of seconds until the session expires.""" 
     134        expiry = self.get('_session_expiry') 
     135        if not expiry:   # Checks both None and 0 cases 
     136            return settings.SESSION_COOKIE_AGE 
     137        if not isinstance(expiry, datetime): 
     138            return expiry 
     139        delta = expiry - datetime.now() 
     140        return delta.days * 86400 + delta.seconds 
     141 
     142    def get_expiry_date(self): 
     143        """Get session the expiry date (as a datetime object).""" 
     144        expiry = self.get('_session_expiry') 
     145        if isinstance(expiry, datetime): 
     146            return expiry 
     147        if not expiry:   # Checks both None and 0 cases 
     148            expiry = settings.SESSION_COOKIE_AGE 
     149        return datetime.now() + timedelta(seconds=expiry) 
     150 
     151    def set_expiry(self, value): 
     152        """ 
     153        Sets a custom expiration for the session. ``value`` can be an integer, a 
     154        Python ``datetime`` or ``timedelta`` object or ``None``. 
     155 
     156        If ``value`` is an integer, the session will expire after that many 
     157        seconds of inactivity. If set to ``0`` then the session will expire on 
     158        browser close. 
     159 
     160        If ``value`` is a ``datetime`` or ``timedelta`` object, the session 
     161        will expire at that specific future time. 
     162 
     163        If ``value`` is ``None``, the session uses the global session expiry 
     164        policy. 
     165        """ 
     166        if value is None: 
     167            # Remove any custom expiration for this session. 
     168            try: 
     169                del self['_session_expiry'] 
     170            except KeyError: 
     171                pass 
     172            return 
     173        if isinstance(value, timedelta): 
     174            value = datetime.now() + value 
     175        self['_session_expiry'] = value 
     176 
     177    def get_expire_at_browser_close(self): 
     178        """ 
     179        Returns ``True`` if the session is set to expire when the browser 
     180        closes, and ``False`` if there's an expiry date. Use 
     181        ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry 
     182        date/age, if there is one. 
     183        """ 
     184        if self.get('_session_expiry') is None: 
     185            return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE 
     186        return self.get('_session_expiry') == 0 
     187 
    131188    # Methods that child classes must implement. 
    132189 
  • django/trunk/django/contrib/sessions/backends/cache.py

    r7294 r7586  
    55class SessionStore(SessionBase): 
    66    """ 
    7     A cache-based session store.  
     7    A cache-based session store. 
    88    """ 
    99    def __init__(self, session_key=None): 
    1010        self._cache = cache 
    1111        super(SessionStore, self).__init__(session_key) 
    12          
     12 
    1313    def load(self): 
    1414        session_data = self._cache.get(self.session_key) 
     
    1616 
    1717    def save(self): 
    18         self._cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE
     18        self._cache.set(self.session_key, self._session, self.get_expiry_age()
    1919 
    2020    def exists(self, session_key): 
     
    2222            return True 
    2323        return False 
    24          
     24 
    2525    def delete(self, session_key): 
    2626        self._cache.delete(session_key) 
  • django/trunk/django/contrib/sessions/backends/db.py

    r7294 r7586  
    4242            session_key = self.session_key, 
    4343            session_data = self.encode(self._session), 
    44             expire_date = datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE
     44            expire_date = self.get_expiry_date(
    4545        ) 
    4646 
  • django/trunk/django/contrib/sessions/middleware.py

    r6634 r7586  
    2727                patch_vary_headers(response, ('Cookie',)) 
    2828            if modified or settings.SESSION_SAVE_EVERY_REQUEST: 
    29                 if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
     29                if request.session.get_expire_at_browser_close()
    3030                    max_age = None 
    3131                    expires = None 
    3232                else: 
    33                     max_age = settings.SESSION_COOKIE_AGE 
    34                     expires_time = time.time() + settings.SESSION_COOKIE_AGE 
     33                    max_age = request.session.get_expiry_age() 
     34                    expires_time = time.time() + max_age 
    3535                    expires = cookie_date(expires_time) 
    36                 # Save the seesion data and refresh the client cookie. 
     36                # Save the session data and refresh the client cookie. 
    3737                request.session.save() 
    3838                response.set_cookie(settings.SESSION_COOKIE_NAME, 
  • django/trunk/django/contrib/sessions/tests.py

    r6890 r7586  
    8989>>> s.pop('some key', 'does not exist') 
    9090'does not exist' 
     91 
     92######################### 
     93# Custom session expiry # 
     94######################### 
     95 
     96>>> from django.conf import settings 
     97>>> from datetime import datetime, timedelta 
     98 
     99>>> td10 = timedelta(seconds=10) 
     100 
     101# A normal session has a max age equal to settings 
     102>>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE 
     103True 
     104 
     105# So does a custom session with an idle expiration time of 0 (but it'll expire 
     106# at browser close) 
     107>>> s.set_expiry(0) 
     108>>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE 
     109True 
     110 
     111# Custom session idle expiration time 
     112>>> s.set_expiry(10) 
     113>>> delta = s.get_expiry_date() - datetime.now() 
     114>>> delta.seconds in (9, 10) 
     115True 
     116>>> age = s.get_expiry_age() 
     117>>> age in (9, 10) 
     118True 
     119 
     120# Custom session fixed expiry date (timedelta) 
     121>>> s.set_expiry(td10) 
     122>>> delta = s.get_expiry_date() - datetime.now() 
     123>>> delta.seconds in (9, 10) 
     124True 
     125>>> age = s.get_expiry_age() 
     126>>> age in (9, 10) 
     127True 
     128 
     129# Custom session fixed expiry date (fixed datetime) 
     130>>> s.set_expiry(datetime.now() + td10) 
     131>>> delta = s.get_expiry_date() - datetime.now() 
     132>>> delta.seconds in (9, 10) 
     133True 
     134>>> age = s.get_expiry_age() 
     135>>> age in (9, 10) 
     136True 
     137 
     138# Set back to default session age 
     139>>> s.set_expiry(None) 
     140>>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE 
     141True 
     142 
     143# Allow to set back to default session age even if no alternate has been set 
     144>>> s.set_expiry(None) 
     145 
     146 
     147# We're changing the setting then reverting back to the original setting at the 
     148# end of these tests. 
     149>>> original_expire_at_browser_close = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE 
     150>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False 
     151 
     152# Custom session age 
     153>>> s.set_expiry(10) 
     154>>> s.get_expire_at_browser_close() 
     155False 
     156 
     157# Custom expire-at-browser-close 
     158>>> s.set_expiry(0) 
     159>>> s.get_expire_at_browser_close() 
     160True 
     161 
     162# Default session age 
     163>>> s.set_expiry(None) 
     164>>> s.get_expire_at_browser_close() 
     165False 
     166 
     167>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True 
     168 
     169# Custom session age 
     170>>> s.set_expiry(10) 
     171>>> s.get_expire_at_browser_close() 
     172False 
     173 
     174# Custom expire-at-browser-close 
     175>>> s.set_expiry(0) 
     176>>> s.get_expire_at_browser_close() 
     177True 
     178 
     179# Default session age 
     180>>> s.set_expiry(None) 
     181>>> s.get_expire_at_browser_close() 
     182True 
     183 
     184>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close 
    91185""" 
    92186 
  • django/trunk/docs/sessions.txt

    r7329 r7586  
    8181 
    8282    * ``__getitem__(key)`` 
     83 
    8384      Example: ``fav_color = request.session['fav_color']`` 
    8485 
    8586    * ``__setitem__(key, value)`` 
     87 
    8688      Example: ``request.session['fav_color'] = 'blue'`` 
    8789 
    8890    * ``__delitem__(key)`` 
     91 
    8992      Example: ``del request.session['fav_color']``. This raises ``KeyError`` 
    9093      if the given ``key`` isn't already in the session. 
    9194 
    9295    * ``__contains__(key)`` 
     96 
    9397      Example: ``'fav_color' in request.session`` 
    9498 
    9599    * ``get(key, default=None)`` 
     100 
    96101      Example: ``fav_color = request.session.get('fav_color', 'red')`` 
    97102 
     
    102107    * ``setdefault()`` (**New in Django development version**) 
    103108 
    104 It also has these three methods: 
     109It also has these methods: 
    105110 
    106111    * ``set_test_cookie()`` 
     112 
    107113      Sets a test cookie to determine whether the user's browser supports 
    108114      cookies. Due to the way cookies work, you won't be able to test this 
     
    111117 
    112118    * ``test_cookie_worked()`` 
     119 
    113120      Returns either ``True`` or ``False``, depending on whether the user's 
    114121      browser accepted the test cookie. Due to the way cookies work, you'll 
     
    117124 
    118125    * ``delete_test_cookie()`` 
     126 
    119127      Deletes the test cookie. Use this to clean up after yourself. 
     128 
     129    * ``set_expiry(value)`` 
     130 
     131      **New in Django development version** 
     132 
     133      Sets the expiration time for the session. You can pass a number of 
     134      different values: 
     135 
     136            * If ``value`` is an integer, the session will expire after that 
     137              many seconds of inactivity. For example, calling 
     138              ``request.session.set_expiry(300)`` would make the session expire 
     139              in 5 minutes. 
     140 
     141            * If ``value`` is a ``datetime`` or ``timedelta`` object, the 
     142              session will expire at that specific time. 
     143       
     144            * If ``value`` is ``0`` then the user's session cookie will expire 
     145              when their browser is closed. 
     146 
     147            * If ``value`` is ``None``, the session reverts to using the global 
     148              session expiry policy. 
     149 
     150    * ``get_expiry_age()`` 
     151 
     152      **New in Django development version** 
     153 
     154      Returns the number of seconds until this session expires. For sessions 
     155      with no custom expiration (or those set to expire at browser close), this 
     156      will equal ``settings.SESSION_COOKIE_AGE``. 
     157 
     158    * ``get_expiry_date()`` 
     159 
     160      **New in Django development version** 
     161 
     162      Returns the date this session will expire. For sessions with no custom 
     163      expiration (or those set to expire at browser close), this will equal the 
     164      date ``settings.SESSION_COOKIE_AGE`` seconds from now. 
     165 
     166    * ``get_expire_at_browser_close()`` 
     167 
     168      **New in Django development version** 
     169 
     170      Returns either ``True`` or ``False``, depending on whether the user's 
     171      session cookie will expire when their browser is closed. 
    120172 
    121173You can edit ``request.session`` at any point in your view. You can edit it 
     
    279331a browser. 
    280332 
     333**New in Django development version** 
     334 
     335This setting is a global default and can be overwritten at a per-session level 
     336by explicitly calling ``request.session.set_expiry()`` as described above in 
     337`using sessions in views`_. 
     338 
    281339Clearing the session table 
    282340==========================