Fixed merging confict
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 · parents 13933ee, a7266ff · Browse files · 9 files·+147 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+147 added−13 removed
- tests:+27 added−0 removed
- other:+120 added−13 removed
Provenance
- Commit
eeb0e94- Tree
ca4e835- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
13933ee- Parent 2
a7266ff
9 files changed+147 added−13 removed
modified:docs/patterns/viewdecorators.rst+49 added
89 unmodified lines90 return decorator91 92 Notice that this assumes an instanciated `cache` object is available, see93 :ref:`caching-pattern` for more information.94+95+96+Templating Decorator97+--------------------98+99+A common pattern invented by the TurboGears guys a while back is a100+templating decorator. The idea of that decorator is that you return a101+dictionary with the values passed to the template from the view function102+and the template is automatically rendered. With that, the following103+three examples do exactly the same::104+105+ @app.route('/')106+ def index():107+ return render_template('index.html', value=42)108+109+ @app.route('/')110+ @templated('index.html')111+ def index():112+ return dict(value=42)113+114+ @app.route('/')115+ @templated()116+ def index():117+ return dict(value=42)118+119+As you can see, if no template name is provided it will use the endpoint120+of the URL map + ``'.html'``. Otherwise the provided template name is121+used. When the decorated function returns, the dictionary returned is122+passed to the template rendering function. If `None` is returned, an123+empty dictionary is assumed.124+125+Here the code for that decorator::126+127+ from functools import wraps128+ from flask import request129+130+ def templated(template=None):131+ def decorator(f):132+ @wraps(f)133+ def decorated_function(*args, **kwargs):134+ template_name = template135+ if template_name is None:136+ template_name = request.endpoint + '.html'137+ ctx = f(*args, **kwargs)138+ if ctx is None:139+ ctx = {}140+ return render_template(template_name, **ctx)141+ return decorated_function142+ return decoratormodified:docs/patterns/wtforms.rst+1 added-1 removed
40 unmodified lines41 user = User(form.username.data, form.email.data,42 form.password.data)43 db_session.add(user)44 flash('Thanks for registering')45- redirect(url_for('login'))45+ return redirect(url_for('login'))46 return render_template('register.html', form=form)47 48 Notice that we are implying that the view is using SQLAlchemy here49 (:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt66 unmodified linesmodified:docs/tutorial/testing.rst+4 added-5 removed
1 Bonus: Testing the Application2 ===============================3 4 Now that you have finished the application and everything works as5-expected, it's probably not the best idea to add automated tests to6-simplify modifications in the future. The application above is used as a7-basic example of how to perform unittesting in the :ref:`testing` section8-of the documentation. Go there to see how easy it is to test Flask9-applications.5+expected, it's probably not a good idea to add automated tests to simplify6+modifications in the future. The application above is used as a basic7+example of how to perform unittesting in the :ref:`testing` section of the8+documentation. Go there to see how easy it is to test Flask applications.modified:docs/api.rst+7 added
181 unmodified lines182 session['objects'].append(42)183 # so mark it as modified yourself184 session.modified = True185 186+ .. attribute:: permanent187 188+ If set to `True` the session life for189+ :attr:`~flask.Flask.permanent_session_lifetime` seconds. The190+ default is 31 days. If set to `False` (which is the default) the191+ session will be deleted when the user closes the browser.192+193+194 Application Globals195 -------------------196 197 To share data that is valid for one request only from one function to81 unmodified linesmodified:docs/quickstart.rst+7 added-2 removed
158 unmodified lines159 `float` like `int` but for floating point values160 `path` like the default but also accepts slashes161 =========== ===========================================162 163+.. _url-building:164+165 URL Building166 ````````````167 168 If it can match URLs, can it also generate them? Of course you can. To169 build a URL to a specific function you can use the :func:`~flask.url_for`170 function. It accepts the name of the function as first argument and a171 number of keyword arguments, each corresponding to the variable part of170-the URL rule. Here some examples:172+the URL rule. Unknown variable parts are appended to the URL as query173+parameter. Here some examples:174 175 >>> from flask import Flask, url_for176 >>> app = Flask(__name__)177 >>> @app.route('/')8 unmodified lines186 >>> with app.test_request_context():187 ... print url_for('index')188 ... print url_for('login')189 ... print url_for('profile', username='John Doe')190+... print url_for('login', next='/')191 ... 192 /193 /login194+/login?next=/195 /user/John%20Doe196 197 (This also uses the :meth:`~flask.Flask.test_request_context` method198 explained below. It basically tells flask to think we are handling a257 unmodified lines456 transmitted in a `POST` or `PUT` request) you can use the457 :attr:`~flask.request.form` attribute. Here a full example of the two458 attributes mentioned above::459 455- @app.route('/login', method=['POST', 'GET'])460+ @app.route('/login', methods=['POST', 'GET'])461 def login():462 error = None463 if request.method == 'POST':464 if valid_login(request.form['username'],177 unmodified linesmodified:docs/testing.rst+19 added
193 unmodified lines194 195 196 .. _MiniTwit Example:197 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/198+199+200+Other Testing Tricks201+--------------------202+203+Besides using the test client we used above there is also the204+:meth:`~flask.Flask.test_request_context` method that in combination with205+the `with` statement can be used to activate a request context206+temporarily. With that you can access the :class:`~flask.request`,207+:class:`~flask.g` and :class:`~flask.session` objects like in view208+functions. Here a full example that showcases this::209+210+ app = flask.Flask(__name__)211+212+ with app.test_request_context('/?name=Peter'):213+ assert flask.request.path == '/'214+ assert flask.request.args['name'] == 'Peter'215+216+All the other objects that are context bound can be used the same.modified: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 307 unmodified linesmodified:flask.py+32 added-4 removed
11 unmodified lines12 from __future__ import with_statement13 import os14 import sys15 import types16+from datetime import datetime, timedelta17 18 from itertools import chain19 from jinja2 import Environment, PackageLoader, FileSystemLoader20 from werkzeug import Request as RequestBase, Response as ResponseBase, \72 unmodified lines93 class _RequestGlobals(object):94 pass95 96 96-class _NullSession(SecureCookie):97+class Session(SecureCookie):98+ """Expands the session for support for switching between permanent99+ and non-permanent sessions.100+ """101+102+ def _get_permanent(self):103+ return self.get('_permanent', False)104+ def _set_permanent(self, value):105+ self['_permanent'] = bool(value)106+ permanent = property(_get_permanent, _set_permanent)107+ del _get_permanent, _set_permanent108+109+110+class _NullSession(Session):111 """Class used to generate nicer error messages if sessions are not112 available. Will still allow read-only access to the empty session113 but fail on setting.114 """56 unmodified lines171 any ``'.index'`` `index` of the application172 any ``'admin.index'`` `index` of the `admin` module173 ==================== ======================= =============================174 175+ Variable arguments that are unknown to the target endpoint are appended176+ to the generated URL as query arguments.177+178+ For more information, head over to the :ref:`Quickstart <url-building>`.179+180 :param endpoint: the endpoint of the URL (name of the function)181 :param values: the variable arguments of the URL rule182 """183 ctx = _request_ctx_stack.top345 unmodified lines529 530 #: The secure cookie uses this for the name of the session cookie531 session_cookie_name = 'session'532 533+ #: A :class:`~datetime.timedelta` which is used to set the expiration534+ #: date of a permanent session. The default is 31 days which makes a535+ #: permanent session survive for roughly one month.536+ permanent_session_lifetime = timedelta(days=31)537+538 #: options that are passed directly to the Jinja2 environment539 jinja_options = ImmutableDict(540 autoescape=True,541 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']145 unmodified lines687 :param request: an instance of :attr:`request_class`.688 """689 key = self.secret_key690 if key is not None:667- return SecureCookie.load_cookie(request, self.session_cookie_name,668- secret_key=key)691+ return Session.load_cookie(request, self.session_cookie_name,692+ secret_key=key)693 694 def save_session(self, session, response):695 """Saves the session if it needs updates. For the default696 implementation, check :meth:`open_session`.2 unmodified lines699 :class:`~werkzeug.contrib.securecookie.SecureCookie`700 object)701 :param response: an instance of :attr:`response_class`702 """703+ expires = None704+ if session.permanent:705+ expires = datetime.utcnow() + self.permanent_session_lifetime679- session.save_cookie(response, self.session_cookie_name)706+ session.save_cookie(response, self.session_cookie_name,707+ expires=expires, httponly=True)708 709 def register_module(self, module, **options):710 """Registers a module with this application. The keyword argument711 of this function are the same as the ones for the constructor of the330 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