Skip to content
Myr

Added missing sessions module

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 0fccfe7 · Browse files · 1 file+168 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+168 added−0 removed

  • other:+168 added−0 removed

1 file+168 added−0 removed

added:flask/sessions.py+168 added
1# -*- coding: utf-8 -*-2"""3 flask.sessions4 ~~~~~~~~~~~~~~56 Implements cookie based sessions based on Werkzeug's secure cookie7 system.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from datetime import datetime14from werkzeug.contrib.securecookie import SecureCookie151617class SessionMixin(object):18 """Expands a basic dictionary with an accessors that are expected19 by Flask extensions and users for the session.20 """2122 def _get_permanent(self):23 return self.get('_permanent', False)2425 def _set_permanent(self, value):26 self['_permanent'] = bool(value)2728 permanent = property(_get_permanent, _set_permanent)29 del _get_permanent, _set_permanent3031 new = False32 modified = True333435class SecureCookieSession(SecureCookie, SessionMixin):36 """Expands the session with support for switching between permanent37 and non-permanent sessions.38 """394041class NullSession(SecureCookieSession):42 """Class used to generate nicer error messages if sessions are not43 available. Will still allow read-only access to the empty session44 but fail on setting.45 """4647 def _fail(self, *args, **kwargs):48 raise RuntimeError('the session is unavailable because no secret '49 'key was set. Set the secret_key on the '50 'application to something unique and secret.')51 __setitem__ = __delitem__ = clear = pop = popitem = \52 update = setdefault = _fail53 del _fail545556class SessionInterface(object):57 """The basic interface you have to implement in order to replace the58 default session interface which uses werkzeug's securecookie59 implementation. The only methods you have to implement are60 :meth:`open_session` and :meth:`save_session`, the others have61 useful defaults which you don't need to change.6263 The session object returned by the :meth:`open_session` method has to64 provide a dictionary like interface plus the properties and methods65 from the :class:`SessionMixin`. We recommend just subclassing a dict66 and adding that mixin::6768 class Session(dict, SessionMixin):69 pass7071 If :meth:`open_session` returns `None` Flask will call into72 :meth:`make_null_session` to create a session that acts as replacement73 if the session support cannot work because some requirement is not74 fulfilled. The default :class:`NullSession` class that is created75 will complain that the secret key was not set.7677 To replace the session interface on an application all you have to do78 is to assign :attr:`flask.Flask.session_interface`::7980 app = Flask(__name__)81 app.session_interface = MySessionInterface()8283 .. versionadded:: 0.784 """8586 #: :meth:`make_null_session` will look here for the class that should87 #: be created when a null session is requested. Likewise the88 #: :meth:`is_null_session` method will perform a typecheck against89 #: this type.90 null_session_class = NullSession9192 def make_null_session(self, app):93 """Creates a null session which acts as a replacement object if the94 real session support could not be loaded due to a configuration95 error. This mainly aids the user experience because the job of the96 null session is to still support lookup without complaining but97 modifications are answered with a helpful error message of what98 failed.99100 This creates an instance of :attr:`null_session_class` by default.101 """102 return self.null_session_class()103104 def is_null_session(self, obj):105 """Checks if a given object is a null session. Null sessions are106 not asked to be saved.107108 This checks if the object is an instance of :attr:`null_session_class`109 by default.110 """111 return isinstance(obj, self.null_session_class)112113 def get_cookie_domain(self, app):114 """Helpful helper method that returns the cookie domain that should115 be used for the session cookie if session cookies are used.116 """117 if app.config['SERVER_NAME'] is not None:118 # chop of the port which is usually not supported by browsers119 return '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]120121 def get_expiration_time(self, app, session):122 """A helper method that returns an expiration date for the session123 or `None` if the session is linked to the browser session. The124 default implementation returns now + the permanent session125 lifetime configured on the application.126 """127 if session.permanent:128 return datetime.utcnow() + app.permanent_session_lifetime129130 def open_session(self, app, request):131 """This method has to be implemented and must either return `None`132 in case the loading failed because of a configuration error or an133 instance of a session object which implements a dictionary like134 interface + the methods and attributes on :class:`SessionMixin`.135 """136 raise NotImplementedError()137138 def save_session(self, app, session, response):139 """This is called for actual sessions returned by :meth:`open_session`140 at the end of the request. This is still called during a request141 context so if you absolutely need access to the request you can do142 that.143 """144 raise NotImplementedError()145146147class SecureCookieSessionInterface(SessionInterface):148 """The cookie session interface that uses the Werkzeug securecookie149 as client side session backend.150 """151 session_class = SecureCookieSession152153 def open_session(self, app, request):154 key = app.secret_key155 if key is not None:156 return self.session_class.load_cookie(request,157 app.session_cookie_name,158 secret_key=key)159160 def save_session(self, app, session, response):161 expires = self.get_expiration_time(app, session)162 domain = self.get_cookie_domain(app)163 if session.modified and not session:164 response.delete_cookie(app.session_cookie_name,165 domain=domain)166 else:167 session.save_cookie(response, app.session_cookie_name,168 expires=expires, httponly=True, domain=domain)