Ticket #2548: session_middleware.17.diff

File session_middleware.17.diff, 10.5 KB (added by SmileyChris, 7 years ago)

Adding "New in Django development version" markers to docs

  • django/contrib/sessions/middleware.py

     
    11from django.conf import settings
    22from django.utils.cache import patch_vary_headers
    33from email.Utils import formatdate
    4 import datetime
    5 import time
    64
    75TEST_COOKIE_NAME = 'testcookie'
    86TEST_COOKIE_VALUE = 'worked'
     
    2523            if accessed:
    2624                patch_vary_headers(response, ('Cookie',))
    2725            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
    28                 if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
     26                if request.session.get_expire_at_browser_close():
    2927                    max_age = None
    3028                    expires = None
    3129                else:
    32                     max_age = settings.SESSION_COOKIE_AGE
    33                     rfcdate = formatdate(time.time() + settings.SESSION_COOKIE_AGE)
    34 
     30                    max_age = request.session.get_max_age()
     31                    expiry_date = request.session.get_expiry_date()
    3532                    # Fixed length date must have '-' separation in the format
    3633                    # DD-MMM-YYYY for compliance with Netscape cookie standard
    37                     expires = datetime.datetime.strftime(datetime.datetime.utcnow() + \
    38                               datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
     34                    expires = expiry_date.strftime('%a, %d-%b-%Y %H:%M:%S GMT')
    3935
    4036                # Save the seesion data and refresh the client cookie.
    4137                request.session.save()
  • django/contrib/sessions/tests.py

     
    7575
    7676>>> s.pop('some key', 'does not exist')
    7777'does not exist'
     78
     79#########################
     80# Custom session expiry #
     81#########################
     82
     83>>> from django.conf import settings
     84>>> from datetime import datetime, timedelta
     85
     86>>> td10 = timedelta(seconds=10)
     87
     88# A normal session has a max age equal to settings
     89>>> s.get_max_age() == settings.SESSION_COOKIE_AGE
     90True
     91
     92# So does a custom session with an idle expiration time of 0 (but it'll expire
     93# at browser close)
     94>>> s.set_expiry(0)
     95>>> s.get_max_age() == settings.SESSION_COOKIE_AGE
     96True
     97
     98# Custom session idle expiration time
     99>>> s.set_expiry(10)
     100>>> delta = s.get_expiry_date() - datetime.utcnow()
     101>>> delta.seconds in (9, 10)
     102True
     103>>> age = s.get_max_age()
     104>>> age in (9, 10)
     105True
     106
     107# Custom session fixed expiry date (timedelta)
     108>>> s.set_expiry(td10)
     109>>> delta = s.get_expiry_date() - datetime.utcnow()
     110>>> delta.seconds in (9, 10)
     111True
     112>>> age = s.get_max_age()
     113>>> age in (9, 10)
     114True
     115
     116# Custom session fixed expiry date (fixed datetime)
     117>>> s.set_expiry(datetime.utcnow() + td10)
     118>>> delta = s.get_expiry_date() - datetime.utcnow()
     119>>> delta.seconds in (9, 10)
     120True
     121>>> age = s.get_max_age()
     122>>> age in (9, 10)
     123True
     124
     125# Set back to default session age
     126>>> s.set_expiry(None)
     127>>> s.get_max_age() == settings.SESSION_COOKIE_AGE
     128True
     129
     130# Allow to set back to default session age even if no alternate has been set
     131>>> s.set_expiry(None)
     132
     133
     134# We're changing the setting then reverting back to the original setting at the
     135# end of these tests.
     136>>> original_expire_at_browser_close = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
     137>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
     138
     139# Custom session age
     140>>> s.set_expiry(10)
     141>>> s.get_expire_at_browser_close()
     142False
     143
     144# Custom expire-at-browser-close
     145>>> s.set_expiry(0)
     146>>> s.get_expire_at_browser_close()
     147True
     148
     149# Default session age
     150>>> s.set_expiry(None)
     151>>> s.get_expire_at_browser_close()
     152False
     153
     154>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
     155
     156# Custom session age
     157>>> s.set_expiry(10)
     158>>> s.get_expire_at_browser_close()
     159False
     160
     161# Custom expire-at-browser-close
     162>>> s.set_expiry(0)
     163>>> s.get_expire_at_browser_close()
     164True
     165
     166# Default session age
     167>>> s.set_expiry(None)
     168>>> s.get_expire_at_browser_close()
     169True
     170
     171>>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close
    78172"""
    79173
    80174if __name__ == '__main__':
  • django/contrib/sessions/backends/base.py

     
    44import random
    55import sys
    66import time
     7from datetime import datetime, timedelta
    78from django.conf import settings
    89from django.core.exceptions import SuspiciousOperation
    910
     
    120121
    121122    _session = property(_get_session)
    122123
     124    def get_max_age(self):
     125        expiry = self.get('_session_expiry')
     126        if not expiry:   # Checks both None and 0 cases
     127            return settings.SESSION_COOKIE_AGE
     128        if not isinstance(expiry, datetime):
     129            return expiry
     130        delta = expiry - datetime.utcnow()
     131        return delta.days * 86400 + delta.seconds
     132
     133    def get_expiry_date(self):
     134        "Returns the expiry date (in UTC)"
     135        expiry = self.get('_session_expiry', settings.SESSION_COOKIE_AGE)
     136        if isinstance(expiry, datetime):
     137            return expiry
     138        return datetime.utcnow() + timedelta(seconds=expiry)
     139
     140    def set_expiry(self, value):
     141        """
     142        Sets a custom expiration for the session. ``value`` can be an integer, a
     143        Python ``datetime`` or ``timedelta`` object or ``None``.
     144
     145        If ``value`` is an integer, the session will expire after that many
     146        seconds of inactivity. If set to ``0`` then the session will expire on
     147        browser close.
     148
     149        If ``value`` is a ``datetime`` or ``timedelta`` object, the session
     150        will expire at that specific future time (``datetime`` objects should be
     151        UTC).
     152
     153        If ``value`` is ``None``, the session uses the global session expiry
     154        policy.
     155        """
     156        if value is None:
     157            # Remove any custom expiration for this session.
     158            try:
     159                del self['_session_expiry']
     160            except KeyError:
     161                pass
     162            return
     163        if isinstance(value, timedelta):
     164            value = datetime.utcnow() + value
     165        self['_session_expiry'] = value
     166
     167    def get_expire_at_browser_close(self):
     168        if self.get('_session_expiry') is None:
     169            return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
     170        return self.get('_session_expiry') == 0
     171
    123172    # Methods that child classes must implement.
    124173
    125174    def exists(self, session_key):
  • AUTHORS

     
    311311    tstromberg@google.com
    312312    Makoto Tsuyuki <mtsuyuki@gmail.com>
    313313    tt@gurgle.no
    314     Amit Upadhyay
     314    Amit Upadhyay <http://www.amitu.com/blog/>
    315315    Geert Vanderkelen
    316316    viestards.lists@gmail.com
    317317    George Vilches <gav@thataddress.com>
  • docs/sessions.txt

     
    8080It implements the following standard dictionary methods:
    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
    98103    * ``keys()``
    99104
    100105    * ``items()``
    101106
    102 It also has these three methods:
     107It also has these methods:
    103108
    104109    * ``set_test_cookie()``
     110
    105111      Sets a test cookie to determine whether the user's browser supports
    106112      cookies. Due to the way cookies work, you won't be able to test this
    107113      until the user's next page request. See "Setting test cookies" below for
    108114      more information.
    109115
    110116    * ``test_cookie_worked()``
     117
    111118      Returns either ``True`` or ``False``, depending on whether the user's
    112119      browser accepted the test cookie. Due to the way cookies work, you'll
    113120      have to call ``set_test_cookie()`` on a previous, separate page request.
    114121      See "Setting test cookies" below for more information.
    115122
    116123    * ``delete_test_cookie()``
     124
    117125      Deletes the test cookie. Use this to clean up after yourself.
    118126
     127    * ``set_expiry(value)``
     128
     129      **New in Django development version**
     130
     131      Sets a custom expiration for the session.
     132
     133      If ``value`` is an integer, the session will expire after that many
     134      seconds of inactivity. If set to ``0`` then the session will expire when
     135      the user's browser is closed.
     136
     137      If ``value`` is a ``datetime`` or ``timedelta`` object, the session will
     138      expire at that specific time (``datetime`` objects must be in UTC).
     139
     140      If ``value`` is ``None``, the session reverts to using the global session
     141      expiry policy.
     142
     143    * ``get_max_age()``
     144
     145      **New in Django development version**
     146
     147      Returns the number of seconds until this session expires. For sessions
     148      with no custom expiration (or those set to expire at browser close), this
     149      will equal ``settings.SESSION_COOKIE_AGE``.
     150
     151    * ``get_expiry_date()``
     152
     153      **New in Django development version**
     154
     155      Returns the date this session will expire. For sessions with no custom
     156      expiration (or those set to expire at browser close), this will equal the
     157      date ``settings.SESSION_COOKIE_AGE`` seconds from now.
     158
     159    * ``get_expire_at_browser_close()``
     160
     161      **New in Django development version**
     162
     163      Returns either ``True`` or ``False``, depending on whether this session
     164      will expire when the user's browser is closed.
     165
    119166You can edit ``request.session`` at any point in your view. You can edit it
    120167multiple times.
    121168
     
    276323her browser. Use this if you want people to have to log in every time they open
    277324a browser.
    278325
     326**New in Django development version**
     327
     328This setting is a global default and can be overwritten by explicitly calling
     329``request.session.set_expiry()`` as described above in
     330`using sessions in views`_.
     331
    279332Clearing the session table
    280333==========================
    281334
Back to Top