Added support for long running sessions. This closes #16.
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 2ba88ee · Browse files · 4 files·+62 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+62 added−5 removed
- tests:+27 added−0 removed
- other:+35 added−5 removed
Provenance
- Commit
36717b0- Tree
047a733- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2ba88ee
4 files changed+62 added−5 removed
modified:docs/api.rst+7 added
172 unmodified lines173 session['objects'].append(42)174 # so mark it as modified yourself175 session.modified = True176 177+ .. attribute:: permanent178 179+ If set to `True` the session life for180+ :attr:`~flask.Flask.permanent_session_lifetime` seconds. The181+ default is 31 days. If set to `False` (which is the default) the182+ session will be deleted when the user closes the browser.183+184+185 Application Globals186 -------------------187 188 To share data that is valid for one request only from one function to81 unmodified linesmodified:tests/flask_tests.py+27 added
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 from __future__ import with_statement13 import os14+import re15 import sys16 import flask17 import unittest18 import tempfile19 import warnings20+from datetime import datetime21+from werkzeug import parse_date22 23 24 example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')25 sys.path.append(os.path.join(example_path, 'flaskr'))94 unmodified lines120 assert flask.session.get('missing_key') is None121 expect_exception(flask.session.__setitem__, 'foo', 42)122 expect_exception(flask.session.pop, 'foo')123 124+ def test_session_expiration(self):125+ permanent = True126+ app = flask.Flask(__name__)127+ app.secret_key = 'testkey'128+ @app.route('/')129+ def index():130+ flask.session['test'] = 42131+ flask.session.permanent = permanent132+ return ''133+ rv = app.test_client().get('/')134+ assert 'set-cookie' in rv.headers135+ match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])136+ expires = parse_date(match.group())137+ expected = datetime.utcnow() + app.permanent_session_lifetime138+ assert expires.year == expected.year139+ assert expires.month == expected.month140+ assert expires.day == expected.day141+142+ permanent = False143+ rv = app.test_client().get('/')144+ assert 'set-cookie' in rv.headers145+ match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])146+ assert match is None147+148 def test_flashes(self):149 app = flask.Flask(__name__)150 app.secret_key = 'testkey'151 246 unmodified linesmodified:flask.py+27 added-4 removed
11 unmodified lines12 from __future__ import with_statement13 import os14 import sys15 import types16+from datetime import datetime, timedelta17 18 from jinja2 import Environment, PackageLoader, FileSystemLoader19 from werkzeug import Request as RequestBase, Response as ResponseBase, \20 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \65 unmodified lines86 class _RequestGlobals(object):87 pass88 89 89-class _NullSession(SecureCookie):90+class Session(SecureCookie):91+ """Expands the session for support for switching between permanent92+ and non-permanent sessions.93+ """94+95+ def _get_permanent(self):96+ return self.get('_permanent', False)97+ def _set_permanent(self, value):98+ self['_permanent'] = bool(value)99+ permanent = property(_get_permanent, _set_permanent)100+ del _get_permanent, _set_permanent101+102+103+class _NullSession(Session):104 """Class used to generate nicer error messages if sessions are not105 available. Will still allow read-only access to the empty session106 but fail on setting.107 """222 unmodified lines330 331 #: The secure cookie uses this for the name of the session cookie332 session_cookie_name = 'session'333 334+ #: A :class:`~datetime.timedelta` which is used to set the expiration335+ #: date of a permanent session. The default is 31 days which makes a336+ #: permanent session survive for roughly one month.337+ permanent_session_lifetime = timedelta(days=31)338+339 #: options that are passed directly to the Jinja2 environment340 jinja_options = ImmutableDict(341 autoescape=True,342 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']168 unmodified lines511 :param request: an instance of :attr:`request_class`.512 """513 key = self.secret_key514 if key is not None:496- return SecureCookie.load_cookie(request, self.session_cookie_name,497- secret_key=key)515+ return Session.load_cookie(request, self.session_cookie_name,516+ secret_key=key)517 518 def save_session(self, session, response):519 """Saves the session if it needs updates. For the default520 implementation, check :meth:`open_session`.2 unmodified lines523 :class:`~werkzeug.contrib.securecookie.SecureCookie`524 object)525 :param response: an instance of :attr:`response_class`526 """527+ expires = None528+ if session.permanent:529+ expires = datetime.utcnow() + self.permanent_session_lifetime508- session.save_cookie(response, self.session_cookie_name)530+ session.save_cookie(response, self.session_cookie_name,531+ expires=expires, httponly=True)532 533 def add_url_rule(self, rule, endpoint, view_func=None, **options):534 """Connects a URL rule. Works exactly like the :meth:`route`535 decorator. If a view_func is provided it will be registered with the312 unmodified linesmodified:Makefile+1 added-1 removed
1-.PHONY: clean-pyc test1+.PHONY: clean-pyc test upload-docs2 3 all: clean-pyc test4 5 test:14 unmodified lines