Skip to content
Myr

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

9 files+147 added−13 removed

modified:docs/patterns/viewdecorators.rst+49 added
89 unmodified lines
90 return decorator9192Notice that this assumes an instanciated `cache` object is available, see93:ref:`caching-pattern` for more information.949596Templating Decorator97--------------------9899A common pattern invented by the TurboGears guys a while back is a100templating decorator. The idea of that decorator is that you return a101dictionary with the values passed to the template from the view function102and the template is automatically rendered. With that, the following103three examples do exactly the same::104105 @app.route('/')106 def index():107 return render_template('index.html', value=42)108109 @app.route('/')110 @templated('index.html')111 def index():112 return dict(value=42)113114 @app.route('/')115 @templated()116 def index():117 return dict(value=42)118119As you can see, if no template name is provided it will use the endpoint120of the URL map + ``'.html'``. Otherwise the provided template name is121used. When the decorated function returns, the dictionary returned is122passed to the template rendering function. If `None` is returned, an123empty dictionary is assumed.124125Here the code for that decorator::126127 from functools import wraps128 from flask import request129130 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 decorator
modified:docs/patterns/wtforms.rst+1 added-1 removed
40 unmodified lines
41 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)4748Notice that we are implying that the view is using SQLAlchemy here49(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt
66 unmodified lines
modified:docs/tutorial/testing.rst+4 added-5 removed
1Bonus: Testing the Application2===============================34Now that you have finished the application and everything works as5expected, it's probably not the best idea to add automated tests to6simplify modifications in the future. The application above is used as a7basic example of how to perform unittesting in the :ref:`testing` section8of the documentation. Go there to see how easy it is to test Flask9applications.5expected, it's probably not a good idea to add automated tests to simplify6modifications in the future. The application above is used as a basic7example of how to perform unittesting in the :ref:`testing` section of the8documentation. Go there to see how easy it is to test Flask applications.
modified:docs/api.rst+7 added
181 unmodified lines
182 session['objects'].append(42)183 # so mark it as modified yourself184 session.modified = True185186 .. attribute:: permanent187188 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.192193194Application Globals195-------------------196197To share data that is valid for one request only from one function to
81 unmodified lines
modified:docs/quickstart.rst+7 added-2 removed
158 unmodified lines
159`float` like `int` but for floating point values160`path` like the default but also accepts slashes161=========== ===========================================162163.. _url-building:164165URL Building166````````````167168If it can match URLs, can it also generate them? Of course you can. To169build a URL to a specific function you can use the :func:`~flask.url_for`170function. It accepts the name of the function as first argument and a171number of keyword arguments, each corresponding to the variable part of170the URL rule. Here some examples:172the URL rule. Unknown variable parts are appended to the URL as query173parameter. Here some examples:174175>>> from flask import Flask, url_for176>>> app = Flask(__name__)177>>> @app.route('/')
8 unmodified lines
186>>> 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%20Doe196197(This also uses the :meth:`~flask.Flask.test_request_context` method198explained below. It basically tells flask to think we are handling a
257 unmodified lines
456transmitted in a `POST` or `PUT` request) you can use the457:attr:`~flask.request.form` attribute. Here a full example of the two458attributes mentioned above::459455 @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 lines
modified:docs/testing.rst+19 added
193 unmodified lines
194195196.. _MiniTwit Example:197 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/198199200Other Testing Tricks201--------------------202203Besides using the test client we used above there is also the204:meth:`~flask.Flask.test_request_context` method that in combination with205the `with` statement can be used to activate a request context206temporarily. With that you can access the :class:`~flask.request`,207:class:`~flask.g` and :class:`~flask.session` objects like in view208functions. Here a full example that showcases this::209210 app = flask.Flask(__name__)211212 with app.test_request_context('/?name=Peter'):213 assert flask.request.path == '/'214 assert flask.request.args['name'] == 'Peter'215216All the other objects that are context bound can be used the same.
modified:tests/flask_tests.py+27 added
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement13import os14import re15import sys16import flask17import unittest18import tempfile19import warnings20from datetime import datetime21from werkzeug import parse_date222324example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')25sys.path.append(os.path.join(example_path, 'flaskr'))
94 unmodified lines
120 assert flask.session.get('missing_key') is None121 expect_exception(flask.session.__setitem__, 'foo', 42)122 expect_exception(flask.session.pop, 'foo')123124 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.day141142 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 None147148 def test_flashes(self):149 app = flask.Flask(__name__)150 app.secret_key = 'testkey'151
307 unmodified lines
modified:flask.py+32 added-4 removed
11 unmodified lines
12from __future__ import with_statement13import os14import sys15import types16from datetime import datetime, timedelta1718from itertools import chain19from jinja2 import Environment, PackageLoader, FileSystemLoader20from werkzeug import Request as RequestBase, Response as ResponseBase, \
72 unmodified lines
93class _RequestGlobals(object):94 pass959696class _NullSession(SecureCookie):97class Session(SecureCookie):98 """Expands the session for support for switching between permanent99 and non-permanent sessions.100 """101102 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_permanent108109110class _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 lines
171 any ``'.index'`` `index` of the application172 any ``'admin.index'`` `index` of the `admin` module173 ==================== ======================= =============================174175 Variable arguments that are unknown to the target endpoint are appended176 to the generated URL as query arguments.177178 For more information, head over to the :ref:`Quickstart <url-building>`.179180 :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.top
345 unmodified lines
529530 #: The secure cookie uses this for the name of the session cookie531 session_cookie_name = 'session'532533 #: 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)537538 #: 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 lines
687 :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)693694 def save_session(self, session, response):695 """Saves the session if it needs updates. For the default696 implementation, check :meth:`open_session`.
2 unmodified lines
699 :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)708709 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 the
330 unmodified lines
modified:Makefile+1 added-1 removed
1.PHONY: clean-pyc test1.PHONY: clean-pyc test upload-docs23all: clean-pyc test45test:
14 unmodified lines