Merge branch 'master' of github.com:mitsuhiko/flask
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 f79ce52, 470014a · Browse files · 20 files·+163 added−58 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+163 added−58 removed
- other:+163 added−58 removed
Provenance
- Commit
5fd81f7- Tree
5287eb7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
f79ce52- Parent 2
470014a
20 files changed+163 added−58 removed
modified:docs/patterns/sqlalchemy.rst+2 added
183 unmodified lines184 185 Then you can either declare the tables in your code like in the examples186 above, or automatically load them::187 188+ from sqlalchemy import Table189+ 190 users = Table('users', metadata, autoload=True)191 192 To insert data you can use the `insert` method. We have to get a193 connection first so that we can use a transaction:25 unmodified linesmodified:docs/blueprints.rst+15 added
200 unmodified lines201 url_for('.index')202 203 This will link to ``admin.index`` for instance in case the current request204 was dispatched to any other admin blueprint endpoint.205+206+Error Handlers207+--------------208+209+Blueprints support the errorhandler decorator just like the :class:`Flask`210+application object, so it is easy to make Blueprint-specific custom error211+pages.212+213+Here is an example for a "404 Page Not Found" exception::214+215+ @simple_page.errorhandler(404)216+ def page_not_found(e):217+ return render_template('pages/404.html')218+219+More information on error handling see :ref:`errorpages`.modified:docs/config.rst+9 added
172 unmodified lines173 jsonify responses will be pretty printed174 if they are not requested by an175 XMLHttpRequest object (controlled by176 the ``X-Requested-With`` header)177+``TEMPLATES_AUTO_RELOAD`` Flask checks if template was modified each178+ time it is requested and reloads it if179+ necessary. But disk I/O is costly and it may180+ be viable to disable this feature by setting181+ this key to ``False``. This option does not182+ affect debug mode.183 ================================= =========================================184 185 .. admonition:: More on ``SERVER_NAME``186 40 unmodified lines227 228 .. versionadded:: 1.0229 ``SESSION_REFRESH_EACH_REQUEST``230 231+.. versionadded:: 1.0232+ ``TEMPLATES_AUTO_RELOAD``233+234 Configuring from Files235 ----------------------236 237 Configuration becomes more useful if you can store it in a separate file,213 unmodified linesmodified:docs/installation.rst+38 added-30 removed
1 unmodified line2 3 Installation4 ============5 6-Flask depends on two external libraries, `Werkzeug6+Flask depends on some external libraries, like `Werkzeug7 <http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/2/>`_.8 Werkzeug is a toolkit for WSGI, the standard Python interface between web9 applications and a variety of servers for both development and deployment.10 Jinja2 renders templates.1 unmodified line12 So how do you get all that on your computer quickly? There are many ways you13 could do that, but the most kick-ass method is virtualenv, so let's have a look14 at that first.15 16-You will need Python 2.6 or higher to get started, so be sure to have an16+You will need Python 2.6 or newer to get started, so be sure to have an17 up-to-date Python 2.x installation. For using Flask with Python 3 have a18 look at :ref:`python3-support`.19 20 .. _virtualenv:45 unmodified lines66 $ mkdir myproject67 $ cd myproject68 $ virtualenv venv69 New python executable in venv/bin/python70- Installing distribute............done.70+ Installing setuptools, pip............done.71 72 Now, whenever you want to work on a project, you only have to activate the73 corresponding environment. On OS X and Linux, do the following::74 37 unmodified lines112 113 $ git clone http://github.com/mitsuhiko/flask.git114 Initialized empty Git repository in ~/dev/flask/.git/115 $ cd flask116- $ virtualenv venv --distribute116+ $ virtualenv venv117 New python executable in venv/bin/python118- Installing distribute............done.118+ Installing setuptools, pip............done.119 $ . venv/bin/activate120 $ python setup.py develop121 ...122 Finished processing dependencies for Flask5 unmodified lines128 To just get the development version without git, do this instead::129 130 $ mkdir flask131 $ cd flask132- $ virtualenv venv --distribute132+ $ virtualenv venv133 $ . venv/bin/activate134 New python executable in venv/bin/python135- Installing distribute............done.135+ Installing setuptools, pip............done.136 $ pip install Flask==dev137 ...138 Finished processing dependencies for Flask==dev139 140 .. _windows-easy-install:141 142-`pip` and `distribute` on Windows143------------------------------------142+`pip` and `setuptools` on Windows143+---------------------------------144 145-On Windows, installation of `easy_install` is a little bit trickier, but still146-quite easy. The easiest way to do it is to download the147-`distribute_setup.py`_ file and run it. The easiest way to run the file is to148-open your downloads folder and double-click on the file.145+Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*146+and *virtualenv* can be a little trickier, but nothing very hard. The two crucial147+packages you will need are setuptools and pip - these will let you install148+anything else (like virtualenv). Fortunately there are two "bootstrap scripts"149+you can run to install either.150 150-Next, add the `easy_install` command and other Python scripts to the151-command search path, by adding your Python installation's Scripts folder152-to the `PATH` environment variable. To do that, right-click on the153-"Computer" icon on the Desktop or in the Start menu, and choose "Properties".154-Then click on "Advanced System settings" (in Windows XP, click on the155-"Advanced" tab instead). Then click on the "Environment variables" button.156-Finally, double-click on the "Path" variable in the "System variables" section,157-and add the path of your Python interpreter's Scripts folder. Be sure to158-delimit it from existing values with a semicolon. Assuming you are using159-Python 2.7 on the default path, add the following value::151+If you don't currently have either, then `get-pip.py` will install both for you152+(you won't need to run ez_setup.py).153 154+`get-pip.py`_155 162- ;C:\Python27\Scripts156+To install the latest setuptools, you can use its bootstrap file:157 164-And you are done! To check that it worked, open the Command Prompt and execute165-``easy_install``. If you have User Account Control enabled on Windows Vista or166-Windows 7, it should prompt you for administrator privileges.158+`ez_setup.py`_159 168-Now that you have ``easy_install``, you can use it to install ``pip``::160+Either should be double-clickable once you download them. If you already have pip,161+you can upgrade them by running::162 170- > easy_install pip163+ > pip install --upgrade pip setuptools164 165+Most often, once you pull up a command prompt you want to be able to type ``pip``166+and ``python`` which will run those things, but this might not automatically happen167+on Windows, because it doesn't know where those executables are (give either a try!).168 173-.. _distribute_setup.py: http://python-distribute.org/distribute_setup.py169+To fix this, you should be able to navigate to your Python install directory170+(e.g ``C:\Python27``), then go to ``Tools``, then ``Scripts``; then find the171+``win_add2path.py`` file and run that. Open a **new** Command Prompt and172+check that you can now just type ``python`` to bring up the interpreter.173+174+Finally, to install `virtualenv`_, you can simply run::175+176+ > pip install virtualenv177+ 178+Then you can be off on your way following the installation instructions above.179+180+.. _get-pip.py: https://raw.github.com/pypa/pip/master/contrib/get-pip.py181+.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.pymodified:docs/unicode.rst+1 added-1 removed
1 Unicode in Flask2 ================3 4-Flask like Jinja2 and Werkzeug is totally Unicode based when it comes to4+Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to5 text. Not only these libraries, also the majority of web related Python6 libraries that deal with text. If you don't know Unicode so far, you7 should probably read `The Absolute Minimum Every Software Developer8 Absolutely, Positively Must Know About Unicode and Character Sets99 unmodified linesmodified:examples/flaskr/schema.sql+1 added-1 removed
1 drop table if exists entries;2 create table entries (3 id integer primary key autoincrement,4 title text not null,5- text text not null5+ 'text' text not null6 );modified:flask/testsuite/blueprints.py+33 added
294 unmodified lines295 self.assert_equal(c.get('/frontend-no').data, b'frontend says no')296 self.assert_equal(c.get('/backend-no').data, b'backend says no')297 self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')298 299+ def test_blueprint_specific_user_error_handling(self):300+ class MyDecoratorException(Exception):301+ pass302+ class MyFunctionException(Exception):303+ pass304+305+ blue = flask.Blueprint('blue', __name__)306+307+ @blue.errorhandler(MyDecoratorException)308+ def my_decorator_exception_handler(e):309+ self.assert_true(isinstance(e, MyDecoratorException))310+ return 'boom'311+312+ def my_function_exception_handler(e):313+ self.assert_true(isinstance(e, MyFunctionException))314+ return 'bam'315+ blue.register_error_handler(MyFunctionException, my_function_exception_handler)316+317+ @blue.route('/decorator')318+ def blue_deco_test():319+ raise MyDecoratorException()320+ @blue.route('/function')321+ def blue_func_test():322+ raise MyFunctionException()323+324+ app = flask.Flask(__name__)325+ app.register_blueprint(blue)326+327+ c = app.test_client()328+329+ self.assert_equal(c.get('/decorator').data, b'boom')330+ self.assert_equal(c.get('/function').data, b'bam')331+332 def test_blueprint_url_definitions(self):333 bp = flask.Blueprint('test', __name__)334 335 @bp.route('/foo', defaults={'baz': 42})488 unmodified linesmodified:flask/testsuite/ext.py+3 added-1 removed
123 unmodified lines124 # On PY3 we even have another one :(125 next = tb.tb_next.tb_next126 if not PY2:127 next = next.tb_next128+ 129+ import os.path128- self.assert_in('flask_broken/__init__.py', next.tb_frame.f_code.co_filename)130+ self.assert_in(os.path.join('flask_broken', '__init__.py'), next.tb_frame.f_code.co_filename)131 132 133 def suite():134 suite = unittest.TestSuite()2 unmodified linesmodified:flask/testsuite/helpers.py+1 added-1 removed
267 unmodified lines268 def test_send_file_object(self):269 app = flask.Flask(__name__)270 with catch_warnings() as captured:271 with app.test_request_context():272- f = open(os.path.join(app.root_path, 'static/index.html'))272+ f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')273 rv = flask.send_file(f)274 rv.direct_passthrough = False275 with app.open_resource('static/index.html') as f:276 self.assert_equal(rv.data, f.read())382 unmodified linesmodified:flask/testsuite/templating.py+8 added
293 unmodified lines294 295 rv = app.test_client().get('/')296 self.assert_equal(rv.data, b'<h1>Jameson</h1>')297 298+ def test_templates_auto_reload(self):299+ app = flask.Flask(__name__)300+ self.assert_true(app.config['TEMPLATES_AUTO_RELOAD'])301+ self.assert_true(app.jinja_env.auto_reload)302+ app = flask.Flask(__name__)303+ app.config['TEMPLATES_AUTO_RELOAD'] = False304+ self.assert_false(app.jinja_env.auto_reload)305 306+307 def suite():308 suite = unittest.TestSuite()309 suite.addTest(unittest.makeSuite(TemplatingTestCase))310 return suitemodified:flask/app.py+12 added
303 unmodified lines304 'PREFERRED_URL_SCHEME': 'http',305 'JSON_AS_ASCII': True,306 'JSON_SORT_KEYS': True,307 'JSONIFY_PRETTYPRINT_REGULAR': True,308+ 'TEMPLATES_AUTO_RELOAD': True,309 })310 311 #: The rule object to use for URL rules created. This is used by312 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.342 unmodified lines655 the Jinja2 globals and filters after initialization. Override656 this function to customize the behavior.657 658 .. versionadded:: 0.5659+ .. versionchanged:: 1.0660+ ``Environment.auto_reload`` set in accordance with661+ ``TEMPLATES_AUTO_RELOAD`` configuration option.662 """663 options = dict(self.jinja_options)664 if 'autoescape' not in options:665 options['autoescape'] = self.select_jinja_autoescape666+ if 'auto_reload' not in options:667+ options['auto_reload'] = self.debug \668+ or self.config['TEMPLATES_AUTO_RELOAD']669 rv = Environment(self, **options)670 rv.globals.update(671 url_for=url_for,672 get_flashed_messages=get_flashed_messages,404 unmodified lines1077 The first `None` refers to the active blueprint. If the error1078 handler should be application wide `None` shall be used.1079 1080 .. versionadded:: 0.71081+ Use :meth:`register_error_handler` instead of modifying1082+ :attr:`error_handler_spec` directly, for application wide error1083+ handlers.1084+ 1085+ .. versionadded:: 0.71086 One can now additionally also register custom exception types1087 that do not necessarily have to be a subclass of the1088 :class:`~werkzeug.exceptions.HTTPException` class.1089 782 unmodified linesmodified:flask/blueprints.py+11 added
397 unmodified lines398 self.record_once(lambda s: s.app._register_error_handler(399 self.name, code_or_exception, f))400 return f401 return decorator402+403+ def register_error_handler(self, code_or_exception, f):404+ """Non-decorator version of the :meth:`errorhandler` error attach405+ function, akin to the :meth:`~flask.Flask.register_error_handler`406+ application-wide function of the :class:`~flask.Flask` object but407+ for error handlers limited to this blueprint.408+409+ .. versionadded:: 0.11410+ """411+ self.record_once(lambda s: s.app._register_error_handler(412+ self.name, code_or_exception, f))modified:flask/helpers.py+7 added-7 removed
197 unmodified lines198 199 For more information, head over to the :ref:`Quickstart <url-building>`.200 201 To integrate applications, :class:`Flask` has a hook to intercept URL build202- errors through :attr:`Flask.build_error_handler`. The `url_for` function203- results in a :exc:`~werkzeug.routing.BuildError` when the current app does204- not have a URL for the given endpoint and values. When it does, the205- :data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if202+ errors through :attr:`Flask.url_build_error_handlers`. The `url_for`203+ function results in a :exc:`~werkzeug.routing.BuildError` when the current204+ app does not have a URL for the given endpoint and values. When it does, the205+ :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if206 it is not `None`, which can return a string to use as the result of207 `url_for` (instead of `url_for`'s default to raise the208 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.209 An example::210 211- def external_url_handler(error, endpoint, **values):211+ def external_url_handler(error, endpoint, values):212 "Looks up an external URL when `url_for` cannot build a URL."213 # This is an example of hooking the build_error_handler.214 # Here, lookup_url is some utility function you've built215 # which looks up the endpoint in some external URL registry.8 unmodified lines224 raise error225 # url_for will use this result, instead of raising BuildError.226 return url227 228- app.build_error_handler = external_url_handler228+ app.url_build_error_handlers.append(external_url_handler)229 230 Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and231- `endpoint` and `**values` are the arguments passed into `url_for`. Note231+ `endpoint` and `values` are the arguments passed into `url_for`. Note232 that this is for building URLs outside the current application, and not for233 handling 404 NotFound errors.234 235 .. versionadded:: 0.10626 unmodified linesmodified:flask/json.py+1 added-1 removed
23 unmodified lines24 except ImportError:25 from itsdangerous import json as _json26 27 28-# figure out if simplejson escapes slashes. This behavior was changed28+# Figure out if simplejson escapes slashes. This behavior was changed29 # from one version to another without reason.30 _slash_escape = '\\/' not in _json.dumps('/')31 32 211 unmodified linesmodified:flask/sessions.py+1 added-1 removed
221 unmodified lines222 return rv223 224 def get_cookie_path(self, app):225 """Returns the path for which the cookie should be valid. The226- default implementation uses the value from the SESSION_COOKIE_PATH``226+ default implementation uses the value from the ``SESSION_COOKIE_PATH``227 config var if it's set, and falls back to ``APPLICATION_ROOT`` or228 uses ``/`` if it's `None`.229 """230 return app.config['SESSION_COOKIE_PATH'] or \135 unmodified linesmodified:flask/signals.py+2 added-2 removed
35 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# the namespace for code signals. If you are not flask code, do40+# The namespace for code signals. If you are not flask code, do41 # not put signals in here. Create your own namespace instead.42 _signals = Namespace()43 44 45-# core signals. For usage examples grep the sourcecode or consult45+# Core signals. For usage examples grep the sourcecode or consult46 # the API documentation in docs/api.rst as well as docs/signals.rst47 template_rendered = _signals.signal('template-rendered')48 request_started = _signals.signal('request-started')49 request_finished = _signals.signal('request-finished')6 unmodified linesmodified:flask/views.py+5 added-5 removed
58 unmodified lines59 #: You can place one or more decorators in this list and whenever the60 #: view function is created the result is automatically decorated.61 #:62 #: .. versionadded:: 0.863- decorators = []63+ decorators = ()64 65 def dispatch_request(self):66 """Subclasses have to override this method to implement the67 actual view function code. This method is called with all20 unmodified lines88 view.__module__ = cls.__module__89 for decorator in cls.decorators:90 view = decorator(view)91 92- # we attach the view class to the view function for two reasons:92+ # We attach the view class to the view function for two reasons:93 # first of all it allows us to easily figure out what class-based94 # view this thing came from, secondly it's also used for instantiating95 # the view class so you can actually replace it with something else96 # for testing purposes and debugging.13 unmodified lines110 methods = set(rv.methods or [])111 for key in d:112 if key in http_method_funcs:113 methods.add(key.upper())114- # if we have no method at all in there we don't want to114+ # If we have no method at all in there we don't want to115 # add a method list. (This is for instance the case for116 # the baseclass or another subclass of a base method view117 # that does not introduce new methods).118 if methods:21 unmodified lines140 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))141 """142 def dispatch_request(self, *args, **kwargs):143 meth = getattr(self, request.method.lower(), None)144- # if the request method is HEAD and we don't have a handler for it145- # retry with GET144+ # If the request method is HEAD and we don't have a handler for it145+ # retry with GET.146 if meth is None and request.method == 'HEAD':147 meth = getattr(self, 'get', None)148 assert meth is not None, 'Unimplemented method %r' % request.method149 return meth(*args, **kwargs)modified:flask/wrappers.py+6 added-6 removed
38 unmodified lines39 provides all of the attributes Werkzeug defines plus a few Flask40 specific ones.41 """42 43- #: the internal URL rule that matched the request. This can be43+ #: The internal URL rule that matched the request. This can be44 #: useful to inspect which methods are allowed for the URL from45 #: a before/after handler (``request.url_rule.methods``) etc.46 #:47 #: .. versionadded:: 0.648 url_rule = None49 50- #: a dict of view arguments that matched the request. If an exception50+ #: A dict of view arguments that matched the request. If an exception51 #: happened when matching, this will be `None`.52 view_args = None53 54- #: if matching the URL failed, this is the exception that will be54+ #: If matching the URL failed, this is the exception that will be55 #: raised / was raised as part of the request handling. This is56 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or57 #: something similar.58 routing_exception = None59 60- # switched by the request context until 1.0 to opt in deprecated61- # module functionality60+ # Switched by the request context until 1.0 to opt in deprecated61+ # module functionality.62 _is_old_module = False63 64 @property65 def max_content_length(self):112 unmodified lines178 179 def _load_form_data(self):180 RequestBase._load_form_data(self)181 182- # in debug mode we're replacing the files multidict with an ad-hoc182+ # In debug mode we're replacing the files multidict with an ad-hoc183 # subclass that raises a different error for key errors.184 ctx = _request_ctx_stack.top185 if ctx is not None and ctx.app.debug and \186 self.mimetype != 'multipart/form-data' and not self.files:13 unmodified linesmodified:scripts/make-release.py+3 added-2 removed
24 unmodified lines25 for line in lineiter:26 match = re.search('^Version\s+(.*)', line.strip())27 if match is None:28 continue29- length = len(match.group(1))29 version = match.group(1).strip()30 if lineiter.next().count('-') != len(match.group(0)):31 continue32 while 1:25 unmodified lines58 59 60 def set_filename_version(filename, version_number, pattern):61 changed = []62+63 def inject_version(match):64 before, old, after = match.groups()65 changed.append(True)66 return before + version_number + after65 unmodified lines132 133 if version in tags:134 fail('Version "%s" is already tagged', version)135 if release_date.date() != date.today():136- fail('Release date is not today (%s != %s)')136+ fail('Release date is not today (%s != %s)',137+ release_date.date(), date.today())138 139 if not git_is_clean():140 fail('You have uncommitted changes in git')141 11 unmodified linesmodified:CHANGES+4 added
19 unmodified lines20 - Added :meth:`flask.Config.from_json`.21 - Added :attr:`flask.Flask.config_class`.22 - Added :meth:`flask.config.Config.get_namespace`.23 24+- Added ``TEMPLATES_AUTO_RELOAD`` config key. If disabled the 25+ templates will be reloaded only if the application is running in 26+ debug mode. For higher performance it’s possible to disable that.27+28 Version 0.10.229 --------------30 31 (bugfix release, release date to be announced)477 unmodified lines