Skip to content
Myr

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

20 files+163 added−58 removed

modified:docs/patterns/sqlalchemy.rst+2 added
183 unmodified lines
184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::187188 from sqlalchemy import Table189 190 users = Table('users', metadata, autoload=True)191192To insert data you can use the `insert` method. We have to get a193connection first so that we can use a transaction:
25 unmodified lines
modified:docs/blueprints.rst+15 added
200 unmodified lines
201 url_for('.index')202203This will link to ``admin.index`` for instance in case the current request204was dispatched to any other admin blueprint endpoint.205206Error Handlers207--------------208209Blueprints support the errorhandler decorator just like the :class:`Flask`210application object, so it is easy to make Blueprint-specific custom error211pages.212213Here is an example for a "404 Page Not Found" exception::214215 @simple_page.errorhandler(404)216 def page_not_found(e):217 return render_template('pages/404.html')218219More information on error handling see :ref:`errorpages`.
modified:docs/config.rst+9 added
172 unmodified lines
173 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================================= =========================================184185.. admonition:: More on ``SERVER_NAME``186
40 unmodified lines
227228.. versionadded:: 1.0229 ``SESSION_REFRESH_EACH_REQUEST``230231.. versionadded:: 1.0232 ``TEMPLATES_AUTO_RELOAD``233234Configuring from Files235----------------------236237Configuration becomes more useful if you can store it in a separate file,
213 unmodified lines
modified:docs/installation.rst+38 added-30 removed
1 unmodified line
23Installation4============56Flask depends on two external libraries, `Werkzeug6Flask depends on some external libraries, like `Werkzeug7<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/2/>`_.8Werkzeug is a toolkit for WSGI, the standard Python interface between web9applications and a variety of servers for both development and deployment.10Jinja2 renders templates.
1 unmodified line
12So how do you get all that on your computer quickly? There are many ways you13could do that, but the most kick-ass method is virtualenv, so let's have a look14at that first.1516You will need Python 2.6 or higher to get started, so be sure to have an16You will need Python 2.6 or newer to get started, so be sure to have an17up-to-date Python 2.x installation. For using Flask with Python 3 have a18look at :ref:`python3-support`.1920.. _virtualenv:
45 unmodified lines
66 $ mkdir myproject67 $ cd myproject68 $ virtualenv venv69 New python executable in venv/bin/python70 Installing distribute............done.70 Installing setuptools, pip............done.7172Now, whenever you want to work on a project, you only have to activate the73corresponding environment. On OS X and Linux, do the following::74
37 unmodified lines
112113 $ 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 Flask
5 unmodified lines
128To just get the development version without git, do this instead::129130 $ 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==dev139140.. _windows-easy-install:141142`pip` and `distribute` on Windows143-----------------------------------142`pip` and `setuptools` on Windows143---------------------------------144145On Windows, installation of `easy_install` is a little bit trickier, but still146quite 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 to148open your downloads folder and double-click on the file.145Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*146and *virtualenv* can be a little trickier, but nothing very hard. The two crucial147packages you will need are setuptools and pip - these will let you install148anything else (like virtualenv). Fortunately there are two "bootstrap scripts"149you can run to install either.150150Next, add the `easy_install` command and other Python scripts to the151command search path, by adding your Python installation's Scripts folder152to the `PATH` environment variable. To do that, right-click on the153"Computer" icon on the Desktop or in the Start menu, and choose "Properties".154Then click on "Advanced System settings" (in Windows XP, click on the155"Advanced" tab instead). Then click on the "Environment variables" button.156Finally, double-click on the "Path" variable in the "System variables" section,157and add the path of your Python interpreter's Scripts folder. Be sure to158delimit it from existing values with a semicolon. Assuming you are using159Python 2.7 on the default path, add the following value::151If you don't currently have either, then `get-pip.py` will install both for you152(you won't need to run ez_setup.py).153154`get-pip.py`_155162 ;C:\Python27\Scripts156To install the latest setuptools, you can use its bootstrap file:157164And 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 or166Windows 7, it should prompt you for administrator privileges.158`ez_setup.py`_159168Now that you have ``easy_install``, you can use it to install ``pip``::160Either should be double-clickable once you download them. If you already have pip,161you can upgrade them by running::162170 > easy_install pip163 > pip install --upgrade pip setuptools164165Most often, once you pull up a command prompt you want to be able to type ``pip``166and ``python`` which will run those things, but this might not automatically happen167on Windows, because it doesn't know where those executables are (give either a try!).168173.. _distribute_setup.py: http://python-distribute.org/distribute_setup.py169To 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 and172check that you can now just type ``python`` to bring up the interpreter.173174Finally, to install `virtualenv`_, you can simply run::175176 > pip install virtualenv177 178Then you can be off on your way following the installation instructions above.179180.. _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.py
modified:docs/unicode.rst+1 added-1 removed
1Unicode in Flask2================34Flask like Jinja2 and Werkzeug is totally Unicode based when it comes to4Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to5text. Not only these libraries, also the majority of web related Python6libraries that deal with text. If you don't know Unicode so far, you7should probably read `The Absolute Minimum Every Software Developer8Absolutely, Positively Must Know About Unicode and Character Sets
99 unmodified lines
modified:examples/flaskr/schema.sql+1 added-1 removed
1drop table if exists entries;2create 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 lines
295 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')298299 def test_blueprint_specific_user_error_handling(self):300 class MyDecoratorException(Exception):301 pass302 class MyFunctionException(Exception):303 pass304305 blue = flask.Blueprint('blue', __name__)306307 @blue.errorhandler(MyDecoratorException)308 def my_decorator_exception_handler(e):309 self.assert_true(isinstance(e, MyDecoratorException))310 return 'boom'311312 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)316317 @blue.route('/decorator')318 def blue_deco_test():319 raise MyDecoratorException()320 @blue.route('/function')321 def blue_func_test():322 raise MyFunctionException()323324 app = flask.Flask(__name__)325 app.register_blueprint(blue)326327 c = app.test_client()328329 self.assert_equal(c.get('/decorator').data, b'boom')330 self.assert_equal(c.get('/function').data, b'bam')331332 def test_blueprint_url_definitions(self):333 bp = flask.Blueprint('test', __name__)334335 @bp.route('/foo', defaults={'baz': 42})
488 unmodified lines
modified:flask/testsuite/ext.py+3 added-1 removed
123 unmodified lines
124 # 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)131132133def suite():134 suite = unittest.TestSuite()
2 unmodified lines
modified:flask/testsuite/helpers.py+1 added-1 removed
267 unmodified lines
268 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 lines
modified:flask/testsuite/templating.py+8 added
293 unmodified lines
294295 rv = app.test_client().get('/')296 self.assert_equal(rv.data, b'<h1>Jameson</h1>')297298 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)305306307def suite():308 suite = unittest.TestSuite()309 suite.addTest(unittest.makeSuite(TemplatingTestCase))310 return suite
modified:flask/app.py+12 added
303 unmodified lines
304 '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 })310311 #: 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 lines
655 the Jinja2 globals and filters after initialization. Override656 this function to customize the behavior.657658 .. 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 lines
1077 The first `None` refers to the active blueprint. If the error1078 handler should be application wide `None` shall be used.10791080 .. 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 lines
modified:flask/blueprints.py+11 added
397 unmodified lines
398 self.record_once(lambda s: s.app._register_error_handler(399 self.name, code_or_exception, f))400 return f401 return decorator402403 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.408409 .. 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 lines
198199 For more information, head over to the :ref:`Quickstart <url-building>`.200201 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::210211 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 lines
224 raise error225 # url_for will use this result, instead of raising BuildError.226 return url227228 app.build_error_handler = external_url_handler228 app.url_build_error_handlers.append(external_url_handler)229230 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.234235 .. versionadded:: 0.10
626 unmodified lines
modified:flask/json.py+1 added-1 removed
23 unmodified lines
24except ImportError:25 from itsdangerous import json as _json262728# 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('/')3132
211 unmodified lines
modified:flask/sessions.py+1 added-1 removed
221 unmodified lines
222 return rv223224 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 lines
modified:flask/signals.py+2 added-2 removed
35 unmodified lines
36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail3940# 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()434445# 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.rst47template_rendered = _signals.signal('template-rendered')48request_started = _signals.signal('request-started')49request_finished = _signals.signal('request-finished')
6 unmodified lines
modified:flask/views.py+5 added-5 removed
58 unmodified lines
59 #: 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 = ()6465 def dispatch_request(self):66 """Subclasses have to override this method to implement the67 actual view function code. This method is called with all
20 unmodified lines
88 view.__module__ = cls.__module__89 for decorator in cls.decorators:90 view = decorator(view)9192 # 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 lines
110 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 lines
140 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 lines
39 provides all of the attributes Werkzeug defines plus a few Flask40 specific ones.41 """4243 #: 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 = None4950 #: 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 = None5354 #: 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 = None5960 # 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 = False6364 @property65 def max_content_length(self):
112 unmodified lines
178179 def _load_form_data(self):180 RequestBase._load_form_data(self)181182 # 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 lines
modified:scripts/make-release.py+3 added-2 removed
24 unmodified lines
25 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 lines
585960def set_filename_version(filename, version_number, pattern):61 changed = []6263 def inject_version(match):64 before, old, after = match.groups()65 changed.append(True)66 return before + version_number + after
65 unmodified lines
132133 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())138139 if not git_is_clean():140 fail('You have uncommitted changes in git')141
11 unmodified lines
modified:CHANGES+4 added
19 unmodified lines
20- Added :meth:`flask.Config.from_json`.21- Added :attr:`flask.Flask.config_class`.22- Added :meth:`flask.config.Config.get_namespace`.2324- 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.2728Version 0.10.229--------------3031(bugfix release, release date to be announced)
477 unmodified lines