Ticket #2548: session_middleware.19.diff
File session_middleware.19.diff, 12.2 KB (added by , 17 years ago) |
---|
-
django/contrib/sessions/middleware.py
26 26 if accessed: 27 27 patch_vary_headers(response, ('Cookie',)) 28 28 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(): 30 30 max_age = None 31 31 expires = None 32 32 else: 33 max_age = settings.SESSION_COOKIE_AGE34 expires_time = time.time() + settings.SESSION_COOKIE_AGE33 max_age = request.session.get_max_age() 34 expires_time = time.time() + max_age 35 35 expires = cookie_date(expires_time) 36 36 # Save the seesion data and refresh the client cookie. 37 37 request.session.save() -
django/contrib/sessions/tests.py
88 88 89 89 >>> s.pop('some key', 'does not exist') 90 90 '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_max_age() == settings.SESSION_COOKIE_AGE 103 True 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_max_age() == settings.SESSION_COOKIE_AGE 109 True 110 111 # Custom session idle expiration time 112 >>> s.set_expiry(10) 113 >>> delta = s.get_expiry_date() - datetime.utcnow() 114 >>> delta.seconds in (9, 10) 115 True 116 >>> age = s.get_max_age() 117 >>> age in (9, 10) 118 True 119 120 # Custom session fixed expiry date (timedelta) 121 >>> s.set_expiry(td10) 122 >>> delta = s.get_expiry_date() - datetime.utcnow() 123 >>> delta.seconds in (9, 10) 124 True 125 >>> age = s.get_max_age() 126 >>> age in (9, 10) 127 True 128 129 # Custom session fixed expiry date (fixed datetime) 130 >>> s.set_expiry(datetime.utcnow() + td10) 131 >>> delta = s.get_expiry_date() - datetime.utcnow() 132 >>> delta.seconds in (9, 10) 133 True 134 >>> age = s.get_max_age() 135 >>> age in (9, 10) 136 True 137 138 # Set back to default session age 139 >>> s.set_expiry(None) 140 >>> s.get_max_age() == settings.SESSION_COOKIE_AGE 141 True 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() 155 False 156 157 # Custom expire-at-browser-close 158 >>> s.set_expiry(0) 159 >>> s.get_expire_at_browser_close() 160 True 161 162 # Default session age 163 >>> s.set_expiry(None) 164 >>> s.get_expire_at_browser_close() 165 False 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() 172 False 173 174 # Custom expire-at-browser-close 175 >>> s.set_expiry(0) 176 >>> s.get_expire_at_browser_close() 177 True 178 179 # Default session age 180 >>> s.set_expiry(None) 181 >>> s.get_expire_at_browser_close() 182 True 183 184 >>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close 91 185 """ 92 186 93 187 if __name__ == '__main__': -
django/contrib/sessions/backends/base.py
4 4 import random 5 5 import sys 6 6 import time 7 from datetime import datetime, timedelta 7 8 from django.conf import settings 8 9 from django.core.exceptions import SuspiciousOperation 9 10 … … 128 129 129 130 _session = property(_get_session) 130 131 132 def get_max_age(self): 133 expiry = self.get('_session_expiry') 134 if not expiry: # Checks both None and 0 cases 135 return settings.SESSION_COOKIE_AGE 136 if not isinstance(expiry, datetime): 137 return expiry 138 delta = expiry - datetime.utcnow() 139 return delta.days * 86400 + delta.seconds 140 141 def get_expiry_date(self): 142 "Returns the expiry date (in UTC)" 143 expiry = self.get('_session_expiry', settings.SESSION_COOKIE_AGE) 144 if isinstance(expiry, datetime): 145 return expiry 146 return datetime.utcnow() + timedelta(seconds=expiry) 147 148 def set_expiry(self, value): 149 """ 150 Sets a custom expiration for the session. ``value`` can be an integer, a 151 Python ``datetime`` or ``timedelta`` object or ``None``. 152 153 If ``value`` is an integer, the session will expire after that many 154 seconds of inactivity. If set to ``0`` then the session will expire on 155 browser close. 156 157 If ``value`` is a ``datetime`` or ``timedelta`` object, the session 158 will expire at that specific future time (``datetime`` objects should be 159 UTC). 160 161 If ``value`` is ``None``, the session uses the global session expiry 162 policy. 163 """ 164 if value is None: 165 # Remove any custom expiration for this session. 166 try: 167 del self['_session_expiry'] 168 except KeyError: 169 pass 170 return 171 if isinstance(value, timedelta): 172 value = datetime.utcnow() + value 173 self['_session_expiry'] = value 174 175 def get_expire_at_browser_close(self): 176 if self.get('_session_expiry') is None: 177 return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE 178 return self.get('_session_expiry') == 0 179 131 180 # Methods that child classes must implement. 132 181 133 182 def exists(self, session_key): -
django/contrib/sessions/backends/cache.py
4 4 5 5 class SessionStore(SessionBase): 6 6 """ 7 A cache-based session store. 7 A cache-based session store. 8 8 """ 9 9 def __init__(self, session_key=None): 10 10 self._cache = cache 11 11 super(SessionStore, self).__init__(session_key) 12 12 13 13 def load(self): 14 14 session_data = self._cache.get(self.session_key) 15 15 return session_data or {} 16 16 17 17 def save(self): 18 self._cache.set(self.session_key, self._session, se ttings.SESSION_COOKIE_AGE)18 self._cache.set(self.session_key, self._session, self.get_max_age()) 19 19 20 20 def exists(self, session_key): 21 21 if self._cache.get(session_key): 22 22 return True 23 23 return False 24 24 25 25 def delete(self, session_key): 26 26 self._cache.delete(session_key) 27 No newline at end of file -
django/contrib/sessions/backends/db.py
10 10 """ 11 11 def __init__(self, session_key=None): 12 12 super(SessionStore, self).__init__(session_key) 13 13 14 14 def load(self): 15 15 try: 16 16 s = Session.objects.get( 17 session_key = self.session_key, 18 expire_date__gt=datetime.datetime. now()17 session_key = self.session_key, 18 expire_date__gt=datetime.datetime.utcnow() 19 19 ) 20 20 return self.decode(s.session_data) 21 21 except (Session.DoesNotExist, SuspiciousOperation): 22 22 23 23 # Create a new session_key for extra security. 24 24 self.session_key = self._get_new_session_key() 25 25 self._session_cache = {} … … 27 27 # Save immediately to minimize collision 28 28 self.save() 29 29 return {} 30 30 31 31 def exists(self, session_key): 32 32 try: 33 33 Session.objects.get(session_key=session_key) 34 34 except Session.DoesNotExist: 35 35 return False 36 36 return True 37 37 38 38 def save(self): 39 39 Session.objects.create( 40 40 session_key = self.session_key, 41 41 session_data = self.encode(self._session), 42 expire_date = datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)42 expire_date = self.get_expiry_date() 43 43 ) 44 44 45 45 def delete(self, session_key): 46 46 try: 47 47 Session.objects.get(session_key=session_key).delete() -
AUTHORS
327 327 tstromberg@google.com 328 328 Makoto Tsuyuki <mtsuyuki@gmail.com> 329 329 tt@gurgle.no 330 Amit Upadhyay 330 Amit Upadhyay <http://www.amitu.com/blog/> 331 331 Geert Vanderkelen 332 332 I.S. van Oostveen <v.oostveen@idca.nl> 333 333 viestards.lists@gmail.com -
docs/sessions.txt
80 80 It implements the following standard dictionary methods: 81 81 82 82 * ``__getitem__(key)`` 83 83 84 Example: ``fav_color = request.session['fav_color']`` 84 85 85 86 * ``__setitem__(key, value)`` 87 86 88 Example: ``request.session['fav_color'] = 'blue'`` 87 89 88 90 * ``__delitem__(key)`` 91 89 92 Example: ``del request.session['fav_color']``. This raises ``KeyError`` 90 93 if the given ``key`` isn't already in the session. 91 94 92 95 * ``__contains__(key)`` 96 93 97 Example: ``'fav_color' in request.session`` 94 98 95 99 * ``get(key, default=None)`` 100 96 101 Example: ``fav_color = request.session.get('fav_color', 'red')`` 97 102 98 103 * ``keys()`` … … 101 106 102 107 * ``setdefault()`` (**New in Django development version**) 103 108 104 It also has these threemethods:109 It also has these methods: 105 110 106 111 * ``set_test_cookie()`` 107 112 Sets a test cookie to determine whether the user's browser supports … … 118 123 * ``delete_test_cookie()`` 119 124 Deletes the test cookie. Use this to clean up after yourself. 120 125 126 * ``set_expiry(value)`` 127 128 **New in Django development version** 129 130 Sets a custom expiration for the session. 131 132 If ``value`` is an integer, the session will expire after that many 133 seconds of inactivity. If set to ``0`` then the session will expire when 134 the user's browser is closed. 135 136 If ``value`` is a ``datetime`` or ``timedelta`` object, the session will 137 expire at that specific time (``datetime`` objects must be in UTC). 138 139 If ``value`` is ``None``, the session reverts to using the global session 140 expiry policy. 141 142 * ``get_max_age()`` 143 144 **New in Django development version** 145 146 Returns the number of seconds until this session expires. For sessions 147 with no custom expiration (or those set to expire at browser close), this 148 will equal ``settings.SESSION_COOKIE_AGE``. 149 150 * ``get_expiry_date()`` 151 152 **New in Django development version** 153 154 Returns the date this session will expire. For sessions with no custom 155 expiration (or those set to expire at browser close), this will equal the 156 UTC date ``settings.SESSION_COOKIE_AGE`` seconds from now. 157 158 * ``get_expire_at_browser_close()`` 159 160 **New in Django development version** 161 162 Returns either ``True`` or ``False``, depending on whether this session 163 will expire when the user's browser is closed. 164 121 165 You can edit ``request.session`` at any point in your view. You can edit it 122 166 multiple times. 123 167 … … 278 322 her browser. Use this if you want people to have to log in every time they open 279 323 a browser. 280 324 325 **New in Django development version** 326 327 This setting is a global default and can be overwritten by explicitly calling 328 ``request.session.set_expiry()`` as described above in 329 `using sessions in views`_. 330 281 331 Clearing the session table 282 332 ========================== 283 333