Merge branch 'new-request-dispatching' into blueprints
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 a4ea315, 086ecdb · Browse files · 28 files·+689 added−266 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+689 added−266 removed
- tests:+45 added−33 removed
- other:+644 added−233 removed
Provenance
- Commit
673fa18- Tree
3746354- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
a4ea315- Parent 2
086ecdb
28 files changed+689 added−266 removed
modified:docs/deploying/others.rst+1 added-1 removed
70 unmodified lines71 `HTTP_HOST`. Werkzeug ships a fixer that will solve some common setups,72 but you might want to write your own WSGI middleware for specific setups.73 74 The most common setup invokes the host being set from `X-Forwarded-Host`75-and the remote address from `X-Forward-For`::75+and the remote address from `X-Forwarded-For`::76 77 from werkzeug.contrib.fixers import ProxyFix78 app.wsgi_app = ProxyFix(app.wsgi_app)79 19 unmodified linesmodified:docs/patterns/fabric.rst+5 added-5 removed
30 unmodified lines31 hosts. These hosts can be defined either in the fabfile or on the command32 line. In this case we will add them to the fabfile.33 34 This is a basic first example that has the ability to upload the current35-sourcecode to the server and install it into a already existing35+sourcecode to the server and install it into a pre-existing36 virtual environment::37 38 from fabric.api import *39 12 unmodified lines52 # upload the source tarball to the temporary folder on the server53 put('dist/%s.tar.gz' % dist, '/tmp/yourapplication.tar.gz')54 # create a place where we can unzip the tarball, then enter55 # that directory and unzip it56- run('mkdir yourapplication')56+ run('mkdir /tmp/yourapplication')57 with cd('/tmp/yourapplication'):58 run('tar xzf /tmp/yourapplication.tar.gz')59- # now setup the package with our virtual environment's60- # python interpreter61- run('/var/www/yourapplication/env/bin/python setup.py install')59+ # now setup the package with our virtual environment's60+ # python interpreter61+ run('/var/www/yourapplication/env/bin/python setup.py install')62 # now that all is set up, delete the folder again63 run('rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz')64 # and finally touch the .wsgi file so that mod_wsgi triggers65 # a reload of the application131 unmodified linesmodified:docs/patterns/packages.rst+1 added-1 removed
55 unmodified lines56 `__name__` variable will resolve to the correct package.57 2. all the view functions (the ones with a :meth:`~flask.Flask.route`58 decorator on top) have to be imported when in the `__init__.py` file.59 Not the object itself, but the module it is in. Import the view module60- *after the application object is created*.60+ **after the application object is created**.61 62 Here's an example `__init__.py`::63 64 from flask import Flask225 unmodified linesmodified:docs/patterns/sqlalchemy.rst+4 added-6 removed
63 unmodified lines64 automatically remove database sessions at the end of the request for you::65 66 from yourapplication.database import db_session67 68- @app.after_request69- def shutdown_session(response):68+ @app.teardown_request69+ def shutdown_session(exception=None):70 db_session.remove()71- return response71 72 Here is an example model (put this into `models.py`, e.g.)::73 74 from sqlalchemy import Column, Integer, String63 unmodified lines138 each request. Put this into your application module::139 140 from yourapplication.database import db_session141 143- @app.after_request144- def shutdown_session(response):142+ @app.teardown_request143+ def shutdown_session(exception=None):144 db_session.remove()146- return response145 146 Here is an example table and model (put this into `models.py`)::147 148 from sqlalchemy import Table, Column, Integer, String66 unmodified linesmodified:docs/patterns/sqlite3.rst+28 added-4 removed
3 unmodified lines4 =========================5 6 In Flask you can implement the opening of database connections at the7 beginning of the request and closing at the end with the8-:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`8+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9 decorators in combination with the special :class:`~flask.g` object.10 11 So here is a simple example of how you can use SQLite 3 with Flask::12 8 unmodified lines21 @app.before_request22 def before_request():23 g.db = connect_db()24 25- @app.after_request26- def after_request(response):25+ @app.teardown_request26+ def teardown_request(exception):27 g.db.close()28- return response28 29+Connect on Demand30+-----------------31+32+The downside of this approach is that this will only work if Flask33+executed the before-request handlers for you. If you are attempting to34+use the database from a script or the interactive Python shell you would35+have to do something like this::36+37+ with app.test_request_context()38+ app.preprocess_request()39+ # now you can use the g.db object40+41+In order to trigger the execution of the connection code. You won't be42+able to drop the dependency on the request context this way, but you could43+make it so that the application connects when necessary::44+45+ def get_connection():46+ db = getattr(g, '_db', None)47+ if db is None:48+ db = g._db = connect_db()49+ return db50+51+Downside here is that you have to use ``db = get_connection()`` instead of52+just being able to use ``g.db`` directly.53+54 .. _easy-querying:55 56 Easy Querying57 -------------54 unmodified linesmodified:docs/tutorial/dbcon.rst+8 added-23 removed
7 unmodified lines8 connection in all our functions so it makes sense to initialize them9 before each request and shut them down afterwards.10 11 Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12-:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13-decorators. In debug mode, if an error is raised,14-:meth:`~flask.Flask.after_request` won't be run, and you'll have access to the15-db connection in the interactive debugger::12+:meth:`~flask.Flask.teardown_request` and :meth:`~flask.Flask.teardown_request`13+decorators::14 15 @app.before_request16 def before_request():17 g.db = connect_db()18 21- @app.after_request22- def after_request(response):23- g.db.close()24- return response25-26-If you want to guarantee that the connection is always closed in debug mode, you27-can close it in a function decorated with :meth:`~flask.Flask.teardown_request`:28-29- @app.before_request30- def before_request():31- g.db = connect_db()32-19 @app.teardown_request20 def teardown_request(exception):21 g.db.close()22 23 Functions marked with :meth:`~flask.Flask.before_request` are called before24 a request and passed no arguments. Functions marked with39-:meth:`~flask.Flask.after_request` are called after a request and25+:meth:`~flask.Flask.teardown_request` are called after a request and26 passed the response that will be sent to the client. They have to return41-that response object or a different one. In this case we just return it42-unchanged.43-44-Functions marked with :meth:`~flask.Flask.teardown_request` get called after the27+that response object or a different one. They are however not guaranteed28+to be executed if an exception is raised, this is where functions marked with29+:meth:`~flask.Flask.teardown_request` come in. They get called after the30 response has been constructed. They are not allowed to modify the request, and31 their return values are ignored. If an exception occurred while the request was47-being processed, it is passed to each function; otherwise, None is passed in.32+being processed, it is passed to each function; otherwise, `None` is passed in.33 34 We store our current database connection on the special :data:`~flask.g`50-object that flask provides for us. This object stores information for one35+object that Flask provides for us. This object stores information for one36 request only and is available from within each function. Never store such37 things on other objects because this would not work with threaded38 environments. That special :data:`~flask.g` object does some magic behind39 the scenes to ensure it does the right thing.2 unmodified linesmodified:docs/tutorial/setup.rst+8 added-1 removed
68 unmodified lines69 if __name__ == '__main__':70 app.run()71 72 With that out of the way you should be able to start up the application73-without problems. When you head over to the server you will get an 40473+without problems. Do this with the following command::74+75+ python flaskr.py76+77+You will see a message telling you that server has started along with78+the address at which you can access it.79+80+When you head over to the server in your browser you will get an 40481 page not found error because we don't have any views yet. But we will82 focus on that a little later. First we should get the database working.83 84 .. admonition:: Externally Visible Server6 unmodified linesmodified:docs/api.rst+11 added-42 removed
242 unmodified lines243 .. autofunction:: send_file244 245 .. autofunction:: send_from_directory246 247+.. autofunction:: safe_join248+249 .. autofunction:: escape250 251 .. autoclass:: Markup252 :members: escape, unescape, striptags56 unmodified lines309 310 Useful Internals311 ----------------312 313+.. autoclass:: flask.ctx.RequestContext314+ :members:315+316 .. data:: _request_ctx_stack317 318 The internal :class:`~werkzeug.local.LocalStack` that is used to implement319 all the context local objects used in Flask. This is a documented29 unmodified lines349 ctx = _request_ctx_stack.top350 if ctx is not None:351 return ctx.session352 348- .. versionchanged:: 0.4349-350- The request context is automatically popped at the end of the request351- for you. In debug mode the request context is kept around if352- exceptions happen so that interactive debuggers have a chance to353- introspect the data. With 0.4 this can also be forced for requests354- that did not fail and outside of `DEBUG` mode. By setting355- ``'flask._preserve_context'`` to `True` on the WSGI environment the356- context will not pop itself at the end of the request. This is used by357- the :meth:`~flask.Flask.test_client` for example to implement the358- deferred cleanup functionality.359-360- You might find this helpful for unittests where you need the361- information from the context local around for a little longer. Make362- sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in363- that situation, otherwise your unittests will leak memory.364-353 Signals354 -------355 356 .. when modifying this list, also update the one in signals.rst29 unmodified lines386 It is sent *before* the standard exception handling kicks in and even387 in debug mode, where no exception handling happens. The exception388 itself is passed to the subscriber as `exception`.389 390+.. data:: request_tearing_down391+392+ This signal is sent when the application is tearing down the request.393+ This is always called, even if an error happened. No arguments are394+ provided.395+396 .. currentmodule:: None397 398 .. class:: flask.signals.Namespace399 9 unmodified lines409 do nothing but will fail with a :exc:`RuntimeError` for all other410 operations, including connecting.411 412 .. _blinker: http://pypi.python.org/pypi/blinker419-420-.. _notes-on-proxies:421-422-Notes On Proxies423-----------------424-425-Some of the objects provided by Flask are proxies to other objects. The426-reason behind this is that these proxies are shared between threads and427-they have to dispatch to the actual object bound to a thread behind the428-scenes as necessary.429-430-Most of the time you don't have to care about that, but there are some431-exceptions where it is good to know that this object is an actual proxy:432-433-- The proxy objects do not fake their inherited types, so if you want to434- perform actual instance checks, you have to do that on the instance435- that is being proxied (see `_get_current_object` below).436-- if the object reference is important (so for example for sending437- :ref:`signals`)438-439-If you need to get access to the underlying object that is proxied, you440-can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::441-442- app = current_app._get_current_object()443- my_signal.send(app)modified:docs/config.rst+33 added-23 removed
49 unmodified lines50 The following configuration values are used internally by Flask:51 52 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|53 54-=============================== =========================================55-``DEBUG`` enable/disable debug mode56-``TESTING`` enable/disable testing mode57-``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58- propagation of exceptions. If not set or59- explicitly set to `None` this is60- implicitly true if either `TESTING` or61- `DEBUG` is true.62-``SECRET_KEY`` the secret key63-``SESSION_COOKIE_NAME`` the name of the session cookie64-``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as65- :class:`datetime.timedelta` object.66-``USE_X_SENDFILE`` enable/disable x-sendfile67-``LOGGER_NAME`` the name of the logger68-``SERVER_NAME`` the name of the server. Required for69- subdomain support (e.g.: ``'localhost'``)70-``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will71- reject incoming requests with a72- content length greater than this by73- returning a 413 status code.74-=============================== =========================================54+================================= =========================================55+``DEBUG`` enable/disable debug mode56+``TESTING`` enable/disable testing mode57+``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58+ propagation of exceptions. If not set or59+ explicitly set to `None` this is60+ implicitly true if either `TESTING` or61+ `DEBUG` is true.62+``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63+ debug mode the request context is not64+ popped on exceptions to enable debuggers65+ to introspect the data. This can be66+ disabled by this key. You can also use67+ this setting to force-enable it for non68+ debug execution which might be useful to69+ debug production applications (but also70+ very risky).71+``SECRET_KEY`` the secret key72+``SESSION_COOKIE_NAME`` the name of the session cookie73+``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as74+ :class:`datetime.timedelta` object.75+``USE_X_SENDFILE`` enable/disable x-sendfile76+``LOGGER_NAME`` the name of the logger77+``SERVER_NAME`` the name of the server. Required for78+ subdomain support (e.g.: ``'localhost'``)79+``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will80+ reject incoming requests with a81+ content length greater than this by82+ returning a 413 status code.83+================================= =========================================84 85 .. admonition:: More on ``SERVER_NAME``86 87 The ``SERVER_NAME`` key is used for the subdomain support. Because22 unmodified lines110 .. versionadded:: 0.6111 ``MAX_CONTENT_LENGTH``112 113 .. versionadded:: 0.7105- ``PROPAGATE_EXCEPTIONS``114+ ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``115 116 Configuring from Files117 ----------------------118 120 unmodified lines239 even create your own script for sourcing that activates a virtualenv240 and exports the development configuration for you.241 - Use a tool like `fabric`_ in production to push code and242 configurations separately to the production server(s). For some234- details about how to do that, head over to the :ref:`deploy` pattern.243+ details about how to do that, head over to the244+ :ref:`fabric-deployment` pattern.245 246 .. _fabric: http://fabfile.org/modified:docs/contents.rst.inc+1 added
15 unmodified lines16 testing17 errorhandling18 config19 signals20+ reqcontext21 shell22 patterns/index23 deploying/index24 becomingbig29 unmodified linesmodified:docs/extensiondev.rst+28 added-7 removed
180 unmodified lines181 182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185- self.app.after_request(self.after_request)185+ self.app.teardown_request(self.teardown_request)186 self.app.before_request(self.before_request)187 188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])1 unmodified line191 def before_request(self):192 ctx = _request_ctx_stack.top193 ctx.sqlite3_db = self.connect()194 195- def after_request(self, response):195+ def teardown_request(self, exception):196 ctx = _request_ctx_stack.top197 ctx.sqlite3_db.close()198- return response198 199 def get_db(self):200 ctx = _request_ctx_stack.top201 if ctx is not None:7 unmodified lines209 SQLite.210 2. We create a class for our extension that requires a supplied `app` object,211 sets a configuration for the database if it's not there212 (:meth:`dict.setdefault`), and attaches `before_request` and214- `after_request` handlers.213+ `teardown_request` handlers.214 3. Next, we define a `connect` function that opens a database connection.215 4. Then we set up the request handlers we bound to the app above. Note here216 that we're attaching our database connection to the top request context via217 `_request_ctx_stack.top`. Extensions should use the top context and not the44 unmodified lines262 263 def init_app(self, app):264 self.app = app265 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267- self.app.after_request(self.after_request)266+ self.app.teardown_request(self.teardown_request)267 self.app.before_request(self.before_request)268 269 def connect(self):270 return sqlite3.connect(app.config['SQLITE3_DATABASE'])1 unmodified line272 def before_request(self):273 ctx = _request_ctx_stack.top274 ctx.sqlite3_db = self.connect()275 277- def after_request(self, response):276+ def teardown_request(self, exception):277 ctx = _request_ctx_stack.top278 ctx.sqlite3_db.close()280- return response279 280 def get_db(self):281 ctx = _request_ctx_stack.top282 if ctx is not None:6 unmodified lines289 and bind their app to the extension in another file::290 291 manager.init_app(app)292 293+End-Of-Request Behavior294+-----------------------295+296+Due to the change in Flask 0.7 regarding functions that are run at the end297+of the request your extension will have to be extra careful there if it298+wants to continue to support older versions of Flask. The following299+pattern is a good way to support both::300+301+ def close_connection(response):302+ ctx = _request_ctx_stack.top303+ ctx.sqlite3_db.close()304+ return response305+306+ if hasattr(app, 'teardown_request'):307+ app.teardown_request(close_connection)308+ else:309+ app.after_request(close_connection)310+311+Strictly speaking the above code is wrong, because teardown functions are312+passed the exception and typically don't return anything. However because313+the return value is discarded this will just work assuming that the code314+in between does not touch the passed parameter.315+316 Learn from Others317 -----------------318 319 This documentation only touches the bare minimum for extension64 unmodified linesmodified:docs/quickstart.rst+5 added
111 unmodified lines112 :align: center113 :class: screenshot114 :alt: screenshot of debugger in action115 116+.. admonition:: Working With Other Debuggers117 118+ Debuggers interfere with each other. If you are using another debugger119+ (e.g. PyDev or IntelliJ), you may need to set ``app.debug = False``.120+121+122 Routing123 -------124 125 Modern web applications have beautiful URLs. This helps people remember625 unmodified linesadded:docs/reqcontext.rst+230 added
1+.. _request-context:2+3+The Request Context4+===================5+6+This document describes the behavior in Flask 0.7 which is mostly in line7+with the old behavior but has some small, subtle differences.8+9+One of the design ideas behind Flask is that there are two different10+“states” in which code is executed. The application setup state in which11+the application implicitly is on the module level. It starts when the12+:class:`Flask` object is instantiated, and it implicitly ends when the13+first request comes in. While the application is in this state a few14+assumptions are true:15+16+- the programmer can modify the application object safely.17+- no request handling happened so far18+- you have to have a reference to the application object in order to19+ modify it, there is no magic proxy that can give you a reference to20+ the application object you're currently creating or modifying.21+22+On the contrast, during request handling, a couple of other rules exist:23+24+- while a request is active, the context local objects25+ (:data:`flask.request` and others) point to the current request.26+- any code can get hold of these objects at any time.27+28+The magic that makes this works is internally referred in Flask as the29+“request context”.30+31+Diving into Context Locals32+--------------------------33+34+Say you have a utility function that returns the URL the user should be35+redirected to. Imagine it would always redirect to the URL's ``next``36+parameter or the HTTP referrer or the index page::37+38+ from flask import request, url_for39+40+ def redirect_url():41+ return request.args.get('next') or \42+ request.referrer or \43+ url_for('index')44+45+As you can see, it accesses the request object. If you try to run this46+from a plain Python shell, this is the exception you will see:47+48+>>> redirect_url()49+Traceback (most recent call last):50+ File "<stdin>", line 1, in <module>51+AttributeError: 'NoneType' object has no attribute 'request'52+53+That makes a lot of sense because we currently do not have a request we54+could access. So we have to make a request and bind it to the current55+context. The :attr:`~flask.Flask.test_request_context` method can create56+us a :class:`~flask.ctx.RequestContext`:57+58+>>> ctx = app.test_request_context('/?next=http://example.com/')59+60+This context can be used in two ways. Either with the `with` statement61+or by calling the :meth:`~flask.ctx.RequestContext.push` and62+:meth:`~flask.ctx.RequestContext.pop` methods:63+64+>>> ctx.push()65+66+From that point onwards you can work with the request object:67+68+>>> redirect_url()69+u'http://example.com/'70+71+Until you call `pop`:72+73+>>> ctx.pop()74+75+Because the request context is internally maintained as a stack you can76+push and pop multiple times. This is very handy to implement things like77+internal redirects.78+79+For more information of how to utilize the request context from the80+interactive Python shell, head over to the :ref:`shell` chapter.81+82+How the Context Works83+---------------------84+85+If you look into how the Flask WSGI application internally works, you will86+find a piece of code that looks very much like this::87+88+ def wsgi_app(self, environ):89+ with self.request_context(environ):90+ try:91+ response = self.full_dispatch_request()92+ except Exception, e:93+ response = self.make_response(self.handle_exception(e))94+ return response(environ, start_response)95+96+The method :meth:`~Flask.request_context` returns a new97+:class:`~flask.ctx.RequestContext` object and uses it in combination with98+the `with` statement to bind the context. Everything that is called from99+the same thread from this point onwards until the end of the `with`100+statement will have access to the request globals (:data:`flask.request`101+and others).102+103+The request context internally works like a stack: The topmost level on104+the stack is the current active request.105+:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on106+the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the107+stack again. On popping the application's108+:func:`~flask.Flask.teardown_request` functions are also executed.109+110+.. _callbacks-and-errors:111+112+Callbacks and Errors113+--------------------114+115+What happens if an error occurs in Flask during request processing? This116+particular behavior changed in 0.7 because we wanted to make it easier to117+understand what is actually happening. The new behavior is quite simple:118+119+1. Before each request, :meth:`~flask.Flask.before_request` functions are120+ executed. If one of these functions return a response, the other121+ functions are no longer called. In any case however the return value122+ is treated as a replacement for the view's return value.123+124+2. If the :meth:`~flask.Flask.before_request` functions did not return a125+ response, the regular request handling kicks in and the view function126+ that was matched has the chance to return a response.127+128+3. The return value of the view is then converted into an actual response129+ object and handed over to the :meth:`~flask.Flask.after_request`130+ functions which have the chance to replace it or modify it in place.131+132+4. At the end of the request the :meth:`~flask.Flask.teardown_request`133+ functions are executed. This always happens, even in case of an134+ unhandled exception down the road.135+136+Now what happens on errors? In production mode if an exception is not137+caught, the 500 internal server handler is called. In development mode138+however the exception is not further processed and bubbles up to the WSGI139+server. That way things like the interactive debugger can provide helpful140+debug information.141+142+An important change in 0.7 is that the internal server error is now no143+longer post processed by the after request callbacks and after request144+callbacks are no longer guaranteed to be executed. This way the internal145+dispatching code looks cleaner and is easier to customize and understand.146+147+The new teardown functions are supposed to be used as a replacement for148+things that absolutely need to happen at the end of request.149+150+Teardown Callbacks151+------------------152+153+The teardown callbacks are special callbacks in that they are executed at154+at different point. Strictly speaking they are independent of the actual155+request handling as they are bound to the lifecycle of the156+:class:`~flask.ctx.RequestContext` object. When the request context is157+popped, the :meth:`~flask.Flask.teardown_request` functions are called.158+159+This is important to know if the life of the request context is prolonged160+by using the test client in a with statement of when using the request161+context from the command line::162+163+ with app.test_client() as client:164+ resp = client.get('/foo')165+ # the teardown functions are still not called at that point166+ # even though the response ended and you have the response167+ # object in your hand168+169+ # only when the code reaches this point the teardown functions170+ # are called. Alternatively the same thing happens if another171+ # request was triggered from the test client172+173+It's easy to see the behavior from the command line:174+175+>>> app = Flask(__name__)176+>>> @app.teardown_request177+... def after_request(exception=None):178+... print 'after request'179+... 180+>>> ctx = app.test_request_context()181+>>> ctx.push()182+>>> ctx.pop()183+after request184+185+.. _notes-on-proxies:186+187+Notes On Proxies188+----------------189+190+Some of the objects provided by Flask are proxies to other objects. The191+reason behind this is that these proxies are shared between threads and192+they have to dispatch to the actual object bound to a thread behind the193+scenes as necessary.194+195+Most of the time you don't have to care about that, but there are some196+exceptions where it is good to know that this object is an actual proxy:197+198+- The proxy objects do not fake their inherited types, so if you want to199+ perform actual instance checks, you have to do that on the instance200+ that is being proxied (see `_get_current_object` below).201+- if the object reference is important (so for example for sending202+ :ref:`signals`)203+204+If you need to get access to the underlying object that is proxied, you205+can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::206+207+ app = current_app._get_current_object()208+ my_signal.send(app)209+210+Context Preservation on Error211+-----------------------------212+213+If an error occurs or not, at the end of the request the request context214+is popped and all data associated with it is destroyed. During215+development however that can be problematic as you might want to have the216+information around for a longer time in case an exception occurred. In217+Flask 0.6 and earlier in debug mode, if an exception occurred, the218+request context was not popped so that the interactive debugger can still219+provide you with important information.220+221+Starting with Flask 0.7 you have finer control over that behavior by222+setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By223+default it's linked to the setting of ``DEBUG``. If the application is in224+debug mode the context is preserved, in production mode it's not.225+226+Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode227+as it will cause your application to leak memory on exceptions. However228+it can be useful during development to get the same error preserving229+behavior as in development mode when attempting to debug an error that230+only occurs under production settings.modified:docs/shell.rst+24 added-41 removed
1+.. _shell:2+3 Working with the Shell4 ======================5 6 .. versionadded:: 0.315 unmodified lines22 that these functions are not only there for interactive shell usage, but23 also for unittesting and other situations that require a faked request24 context.25 24-Diving into Context Locals26+Generally it's recommended that you read the :ref:`request-context`27+chapter of the documentation first.28+29+Creating a Request Context30 --------------------------31 27-Say you have a utility function that returns the URL the user should be28-redirected to. Imagine it would always redirect to the URL's ``next``29-parameter or the HTTP referrer or the index page::32+The easiest way to create a proper request context from the shell is by33+using the :attr:`~flask.Flask.test_request_context` method which creates34+us a :class:`~flask.ctx.RequestContext`:35 31- from flask import request, url_for36+>>> ctx = app.test_request_context()37 33- def redirect_url():34- return request.args.get('next') or \35- request.referrer or \36- url_for('index')38+Normally you would use the `with` statement to make this request object39+active, but in the shell it's easier to use the40+:meth:`~flask.ctx.RequestContext.push` and41+:meth:`~flask.ctx.RequestContext.pop` methods by hand:42 38-As you can see, it accesses the request object. If you try to run this39-from a plain Python shell, this is the exception you will see:40-41->>> redirect_url()42-Traceback (most recent call last):43- File "<stdin>", line 1, in <module>44-AttributeError: 'NoneType' object has no attribute 'request'45-46-That makes a lot of sense because we currently do not have a request we47-could access. So we have to make a request and bind it to the current48-context. The :attr:`~flask.Flask.test_request_context` method can create49-us a request context:50-51->>> ctx = app.test_request_context('/?next=http://example.com/')52-53-This context can be used in two ways. Either with the `with` statement54-(which unfortunately is not very handy for shell sessions). The55-alternative way is to call the `push` and `pop` methods:56-43 >>> ctx.push()44 59-From that point onwards you can work with the request object:45+From that point onwards you can work with the request object until you46+call `pop`:47 61->>> redirect_url()62-u'http://example.com/'63-64-Until you call `pop`:65-48 >>> ctx.pop()67->>> redirect_url()68-Traceback (most recent call last):69- File "<stdin>", line 1, in <module>70-AttributeError: 'NoneType' object has no attribute 'request'49 72-50 Firing Before/After Request51 ---------------------------52 53 By just creating a request context, you still don't have run the code that77-is normally run before a request. This probably results in your database78-being unavailable, the current user not being stored on the54+is normally run before a request. This might result in your database55+being unavailable if you are connecting to the database in a56+before-request callback or the current user not being stored on the57 :data:`~flask.g` object etc.58 59 This however can easily be done yourself. Just call60 :meth:`~flask.Flask.preprocess_request`:12 unmodified lines73 >>> app.process_response(app.response_class())74 <Response 0 bytes [200 OK]>75 >>> ctx.pop()76 77+The functions registered as :meth:`~flask.Flask.teardown_request` are78+automatically called when the context is popped. So this is the perfect79+place to automatically tear down resources that were needed by the request80+context (such as database connections).81 82+83 Further Improving the Shell Experience84 --------------------------------------85 86 If you like the idea of experimenting in a shell, create yourself a module7 unmodified linesmodified:docs/signals.rst+16 added
234 unmodified lines235 236 from flask import got_request_exception237 got_request_exception.connect(log_exception, app)238 239+.. data:: flask.request_tearing_down240+ :noindex:241+242+ This signal is sent when the request is tearing down. This is always243+ called, even if an exception is caused. Currently functions listening244+ to this signal are called after the regular teardown handlers, but this245+ is not something you can rely on.246+247+ Example subscriber::248+249+ def close_db_connection(sender):250+ session.close()251+252+ from flask import request_tearing_down253+ request_tearing_down.connect(close_db_connection, app)254+255 .. _blinker: http://pypi.python.org/pypi/blinkermodified:docs/upgrading.rst+47 added
20 unmodified lines21 22 Version 0.723 -----------24 25+The following backwards incompatible changes exist from 0.6 to 0.726+27+Bug in Request Locals28+`````````````````````29+30 Due to a bug in earlier implementations the request local proxies now31 raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they32 are unbound. If you caught these exceptions with :exc:`AttributeError`33 before, you should catch them with :exc:`RuntimeError` now.14 unmodified lines48 New code::49 50 return send_file(my_file_object, add_etags=False)51 52+.. _upgrading-to-new-teardown-handling:53+54+Upgrading to new Teardown Handling55+``````````````````````````````````56+57+We streamlined the behavior of the callbacks for request handling. For58+things that modify the response the :meth:`~flask.Flask.after_request`59+decorators continue to work as expected, but for things that absolutely60+must happen at the end of request we introduced the new61+:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that62+change also made after-request work differently under error conditions.63+It's not consistently skipped if exceptions happen whereas previously it64+might have been called twice to ensure it is executed at the end of the65+request.66+67+If you have database connection code that looks like this::68+69+ @app.after_request70+ def after_request(response):71+ g.db.close()72+ return response73+74+You are now encouraged to use this instead::75+76+ @app.teardown_request77+ def after_request(exception):78+ g.db.close()79+80+On the upside this change greatly improves the internal code flow and81+makes it easier to customize the dispatching and error handling. This82+makes it now a lot easier to write unit tests as you can prevent closing83+down of database connections for a while. You can take advantage of the84+fact that the teardown callbacks are called when the response context is85+removed from the stack so a test can query the database after request86+handling::87+88+ with app.test_client() as client:89+ resp = client.get('/')90+ # g.db is still bound if there is such a thing91+92+ # and here it's gone93+94 Version 0.695 -----------96 97 Flask 0.6 comes with a backwards incompatible change which affects the87 unmodified linesmodified:examples/flaskr/flaskr.py+2 added-3 removed
45 unmodified lines46 """Make sure we are connected to the database each request."""47 g.db = connect_db()48 49 50-@app.after_request51-def after_request(response):50+@app.teardown_request51+def teardown_request(exception):52 """Closes the database again at the end of the request."""53 g.db.close()54- return response54 55 56 @app.route('/')57 def show_entries():40 unmodified linesmodified:examples/minitwit/minitwit.py+2 added-3 removed
80 unmodified lines81 g.user = query_db('select * from user where user_id = ?',82 [session['user_id']], one=True)83 84 85-@app.after_request86-def after_request(response):85+@app.teardown_request86+def teardown_request(exception):87 """Closes the database again at the end of the request."""88 g.db.close()89- return response89 90 91 @app.route('/')92 def timeline():155 unmodified linesmodified:flask/__init__.py+2 added-2 removed
17 unmodified lines18 from .app import Flask, Request, Response19 from .config import Config20 from .helpers import url_for, jsonify, json_available, flash, \21 send_file, send_from_directory, get_flashed_messages, \22- get_template_attribute, make_response22+ get_template_attribute, make_response, safe_join23 from .globals import current_app, g, request, session, _request_ctx_stack24 from .ctx import has_request_context25 from .module import Module26 from .templating import render_template, render_template_string27 from .session import Session28 29 # the signals30 from .signals import signals_available, template_rendered, request_started, \31- request_finished, got_request_exception31+ request_finished, got_request_exception, request_tearing_down32 33 # only import json if it's available34 if json_available:35 from .helpers import jsonmodified:flask/app.py+105 added-52 removed
23 unmodified lines24 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _tojson_filter, _endpoint_from_view_func26 from .wrappers import Request, Response27 from .config import ConfigAttribute, Config28-from .ctx import _RequestContext28+from .ctx import RequestContext29 from .globals import _request_ctx_stack, request30 from .session import Session, _NullSession31 from .module import _ModuleSetupState32 from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34-from .signals import request_started, request_finished, got_request_exception34+from .signals import request_started, request_finished, got_request_exception, \35+ request_tearing_down36 37 # a lock used for logger initialization38 _logger_lock = Lock()39 84 unmodified lines124 #: Flask extensions (and in the future probably also Flask itself).125 #: For example this might activate unittest helpers that have an126 #: additional runtime cost which should not be enabled by default.127 #:128+ #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the129+ #: default it's implicitly enabled.130+ #:131 #: This attribute can also be configured from the config with the132 #: `TESTING` configuration key. Defaults to `False`.133 testing = ConfigAttribute('TESTING')134 62 unmodified lines197 default_config = ImmutableDict({198 'DEBUG': False,199 'TESTING': False,200 'PROPAGATE_EXCEPTIONS': None,201+ 'PRESERVE_CONTEXT_ON_EXCEPTION': None,202 'SECRET_KEY': None,203 'SESSION_COOKIE_NAME': 'session',204 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),205 'USE_X_SENDFILE': False,138 unmodified lines344 return rv345 return self.testing or self.debug346 347 @property348+ def preserve_context_on_exception(self):349+ """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`350+ configuration value in case it's set, otherwise a sensible default351+ is returned.352+353+ .. versionadded:: 0.7354+ """355+ rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']356+ if rv is not None:357+ return rv358+ return self.debug359+360+ @property361 def logger(self):362 """A :class:`logging.Logger` object for this application. The363 default configuration is to log to stderr if the application is364 in debug mode. This logger can be used to (surprise) log messages.423 unmodified lines788 self.before_request_funcs.setdefault(None, []).append(f)789 return f790 791 def after_request(self, f):774- """Register a function to be run after each request."""792+ """Register a function to be run after each request. Your function793+ must take one parameter, a :attr:`response_class` object and return794+ a new response object or the same (see :meth:`process_response`).795+796+ As of Flask 0.7 this function might not be executed at the end of the797+ request in case an unhandled exception ocurred.798+ """799 self.after_request_funcs.setdefault(None, []).append(f)800 return f801 802 def teardown_request(self, f):803 """Register a function to be run at the end of each request,780- regardless of whether there was an exception or not.804+ regardless of whether there was an exception or not. These functions805+ are executed when the request context is popped, even if not an806+ actual request was performed.807+808+ Example::809+810+ ctx = app.test_request_context()811+ ctx.push()812+ ...813+ ctx.pop()814+815+ When ``ctx.pop()`` is executed in the above example, the teardown816+ functions are called just before the request context moves from the817+ stack of active contexts. This becomes relevant if you are using818+ such constructs in tests.819+820+ Generally teardown functions must take every necesary step to avoid821+ that they will fail. If they do execute code that might fail they822+ will have to surround the execution of these code by try/except823+ statements and log ocurring errors.824 """825 self.teardown_request_funcs.setdefault(None, []).append(f)826 return f827 22 unmodified lines850 exists, a default 500 internal server error message is displayed.851 852 .. versionadded: 0.3853 """854+ exc_type, exc_value, tb = sys.exc_info()855+856 got_request_exception.send(self, exception=e)857 handler = self.error_handlers.get(500)858+859 if self.propagate_exceptions:860+ # if we want to repropagate the exception, we can attempt to861+ # raise it with the whole traceback in case we can do that862+ # (the function was actually called from the except part)863+ # otherwise, we just raise the error again864+ if exc_value is e:865+ raise exc_type, exc_value, tb866+ else:814- raise867+ raise e868+869 self.logger.exception('Exception on %s [%s]' % (870 request.path,871 request.method872 ))5 unmodified lines878 """Does the request dispatching. Matches the URL and returns the879 return value of the view or error handler. This does not have to880 be a response object. In order to convert the return value to a881 proper response object, call :func:`make_response`.882+883+ .. versionchanged:: 0.7884+ This no longer does the exception handling, this code was885+ moved to the new :meth:`full_dispatch_request`.886 """887 req = _request_ctx_stack.top.request888+ if req.routing_exception is not None:889+ raise req.routing_exception890+ rule = req.url_rule891+ # if we provide automatic options for this URL and the892+ # request came with the OPTIONS method, reply automatically893+ if getattr(rule, 'provide_automatic_options', False) \894+ and req.method == 'OPTIONS':895+ return self.make_default_options_response()896+ # otherwise dispatch to the handler for that endpoint897+ return self.view_functions[rule.endpoint](**req.view_args)898+899+ def full_dispatch_request(self):900+ """Dispatches the request and on top of that performs request901+ pre and postprocessing as well as HTTP exception catching and902+ error handling.903+904+ .. versionadded:: 0.7905+ """906 try:831- if req.routing_exception is not None:832- raise req.routing_exception833- rule = req.url_rule834- # if we provide automatic options for this URL and the835- # request came with the OPTIONS method, reply automatically836- if getattr(rule, 'provide_automatic_options', False) \837- and req.method == 'OPTIONS':838- return self.make_default_options_response()839- # otherwise dispatch to the handler for that endpoint840- return self.view_functions[rule.endpoint](**req.view_args)907+ request_started.send(self)908+ rv = self.preprocess_request()909+ if rv is None:910+ rv = self.dispatch_request()911 except HTTPException, e:842- return self.handle_http_exception(e)912+ rv = self.handle_http_exception(e)913+ response = self.make_response(rv)914+ response = self.process_response(response)915+ request_finished.send(self, response=response)916+ return response917 918 def make_default_options_response(self):919 """This method is called to create the default `OPTIONS` response.920 This can be changed through subclassing to change the default101 unmodified lines1022 return response1023 1024 def do_teardown_request(self):1025 """Called after the actual request dispatching and will952- call every as :meth:`teardown_request` decorated function.1026+ call every as :meth:`teardown_request` decorated function. This is1027+ not actually called by the :class:`Flask` object itself but is always1028+ triggered when the request context is popped. That way we have a1029+ tighter control over certain resources under testing environments.1030 """1031 funcs = reversed(self.teardown_request_funcs.get(None, ()))1032 mod = request.module1033 if mod and mod in self.teardown_request_funcs:2 unmodified lines1036 for func in funcs:1037 rv = func(exc)1038 if rv is not None:1039 return rv1040+ request_tearing_down.send(self)1041 1042 def request_context(self, environ):965- """Creates a request context from the given environment and binds966- it to the current context. This must be used in combination with967- the `with` statement because the request is only bound to the968- current context for the duration of the `with` block.1043+ """Creates a :class:`~flask.ctx.RequestContext` from the given1044+ environment and binds it to the current context. This must be used in1045+ combination with the `with` statement because the request is only bound1046+ to the current context for the duration of the `with` block.1047 1048 Example usage::1049 1050 with app.request_context(environ):9 unmodified lines1060 do_something_with(request)1061 finally:1062 ctx.pop()1063 986- The big advantage of this approach is that you can use it without987- the try/finally statement in a shell for interactive testing:988-989- >>> ctx = app.test_request_context()990- >>> ctx.bind()991- >>> request.path992- u'/'993- >>> ctx.unbind()994-1064 .. versionchanged:: 0.31065 Added support for non-with statement usage and `with` statement1066 is now passed the ctx object.1067 1068 :param environ: a WSGI environment1069 """1001- return _RequestContext(self, environ)1070+ return RequestContext(self, environ)1071 1072 def test_request_context(self, *args, **kwargs):1073 """Creates a WSGI environment from the given values (see1074 :func:`werkzeug.create_environ` for more information, this26 unmodified lines1101 1102 Then you still have the original application object around and1103 can continue to call methods on it.1104 1036- .. versionchanged:: 0.41037- The :meth:`after_request` functions are now called even if an1038- error handler took over request processing. This ensures that1039- even if an exception happens database have the chance to1040- properly close the connection.1041-1105 .. versionchanged:: 0.71043- The :meth:`teardown_request` functions get called at the very end of1044- processing the request. If an exception was thrown, it gets passed to1045- each teardown_request function.1106+ The behavior of the before and after request callbacks was changed1107+ under error conditions and a new callback was added that will1108+ always execute at the end of the request, independent on if an1109+ error ocurred or not. See :ref:`callbacks-and-errors`.1110 1111 :param environ: a WSGI environment1112 :param start_response: a callable accepting a status code,1113 a list of headers and an optional1114 exception context to start the response1115 """1116 with self.request_context(environ):1117 try:1054- request_started.send(self)1055- rv = self.preprocess_request()1056- if rv is None:1057- rv = self.dispatch_request()1058- response = self.make_response(rv)1118+ response = self.full_dispatch_request()1119 except Exception, e:1120 response = self.make_response(self.handle_exception(e))1061- try:1062- response = self.process_response(response)1063- except Exception, e:1064- response = self.make_response(self.handle_exception(e))1065- finally:1066- self.do_teardown_request()1067- request_finished.send(self, response=response)1121 return response(environ, start_response)1122 1123 def __call__(self, environ, start_response):1124 """Shortcut for :attr:`wsgi_app`."""1 unmodified linemodified:flask/config.py+2 added-2 removed
139 unmodified lines140 - an actual object reference: that object is used directly141 142 Objects are usually either modules or classes.143 144- Just the uppercase variables in that object are stored in the config145- after lowercasing. Example usage::144+ Just the uppercase variables in that object are stored in the config.145+ Example usage::146 147 app.config.from_object('yourapplication.default_config')148 from yourapplication import default_config149 app.config.from_object(default_config)16 unmodified linesmodified:flask/ctx.py+31 added-4 removed
49 unmodified lines50 """51 return _request_ctx_stack.top is not None52 53 54-class _RequestContext(object):54+class RequestContext(object):55 """The request context contains all request relevant information. It is56 created at the beginning of the request and pushed to the57 `_request_ctx_stack` and removed at the end of it. It will create the58 URL adapter and request object for the WSGI environment provided.59+60+ Do not attempt to use this class directly, instead use61+ :meth:`~flask.Flask.test_request_context` and62+ :meth:`~flask.Flask.request_context` to create this object.63+64+ When the request context is popped, it will evaluate all the65+ functions registered on the application for teardown execution66+ (:meth:`~flask.Flask.teardown_request`).67+68+ The request context is automatically popped at the end of the request69+ for you. In debug mode the request context is kept around if70+ exceptions happen so that interactive debuggers have a chance to71+ introspect the data. With 0.4 this can also be forced for requests72+ that did not fail and outside of `DEBUG` mode. By setting73+ ``'flask._preserve_context'`` to `True` on the WSGI environment the74+ context will not pop itself at the end of the request. This is used by75+ the :meth:`~flask.Flask.test_client` for example to implement the76+ deferred cleanup functionality.77+78+ You might find this helpful for unittests where you need the79+ information from the context local around for a little longer. Make80+ sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in81+ that situation, otherwise your unittests will leak memory.82 """83 84 def __init__(self, app, environ):85 self.app = app10 unmodified lines96 except HTTPException, e:97 self.request.routing_exception = e98 99 def push(self):77- """Binds the request context."""100+ """Binds the request context to the current context."""101 _request_ctx_stack.push(self)102 103 # Open the session at the moment that the request context is104 # available. This allows a custom open_session method to use the2 unmodified lines107 if self.session is None:108 self.session = _NullSession()109 110 def pop(self):88- """Pops the request context."""111+ """Pops the request context and unbinds it by doing that. This will112+ also trigger the execution of functions registered by the113+ :meth:`~flask.Flask.teardown_request` decorator.114+ """115+ self.app.do_teardown_request()116 _request_ctx_stack.pop()117 118 def __enter__(self):119 self.push()5 unmodified lines125 # access the request object in the interactive shell. Furthermore126 # the context can be force kept alive for the test client.127 # See flask.testing for how this works.128 if not self.request.environ.get('flask._preserve_context') and \102- (tb is None or not self.app.debug):129+ (tb is None or not self.app.preserve_context_on_exception):130 self.pop()modified:flask/helpers.py+31 added-10 removed
169 unmodified lines170 any ``'admin.index'`` `index` of the `admin` module171 ==================== ======================= =============================172 173 Variable arguments that are unknown to the target endpoint are appended174- to the generated URL as query arguments.174+ to the generated URL as query arguments. If the value of a query argument175+ is `None`, the whole pair is skipped.176 177 For more information, head over to the :ref:`Quickstart <url-building>`.178 179 :param endpoint: the endpoint of the URL (name of the function)73 unmodified lines253 :param with_categories: set to `True` to also receive categories.254 """255 flashes = _request_ctx_stack.top.flashes256 if flashes is None:256- _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])257+ _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \258+ if '_flashes' in session else []259 if not with_categories:260 return [x[1] for x in flashes]261 return flashes262 64 unmodified lines327 # removed in Flask 1.0328 if not attachment_filename and not mimetype \329 and isinstance(filename, basestring):330 warn(DeprecationWarning('The filename support for file objects '329- 'passed to send_file is not deprecated. Pass an '331+ 'passed to send_file is now deprecated. Pass an '332 'attach_filename if you want mimetypes to be guessed.'),333 stacklevel=2)334 if add_etags:335 warn(DeprecationWarning('In future flask releases etags will no '58 unmodified lines394 rv.headers.pop('x-sendfile', None)395 return rv396 397 398+def safe_join(directory, filename):399+ """Safely join `directory` and `filename`.400+401+ Example usage::402+403+ @app.route('/wiki/<path:filename>')404+ def wiki_page(filename):405+ filename = safe_join(app.config['WIKI_FOLDER'], filename)406+ with open(filename, 'rb') as fd:407+ content = fd.read() # Read and process the file content...408+409+ :param directory: the base directory.410+ :param filename: the untrusted filename relative to that directory.411+ :raises: :class:`~werkzeug.exceptions.NotFound` if the retsulting path412+ would fall out of `directory`.413+ """414+ filename = posixpath.normpath(filename)415+ for sep in _os_alt_seps:416+ if sep in filename:417+ raise NotFound()418+ if os.path.isabs(filename) or filename.startswith('../'):419+ raise NotFound()420+ return os.path.join(directory, filename)421+422+423 def send_from_directory(directory, filename, **options):424 """Send a file from a given directory with :func:`send_file`. This425 is a secure way to quickly expose static files from an upload folder426 or something similar.19 unmodified lines446 download.447 :param options: optional keyword arguments that are directly448 forwarded to :func:`send_file`.449 """423- filename = posixpath.normpath(filename)424- for sep in _os_alt_seps:425- if sep in filename:426- raise NotFound()427- if os.path.isabs(filename) or filename.startswith('../'):428- raise NotFound()429- filename = os.path.join(directory, filename)450+ filename = safe_join(directory, filename)451 if not os.path.isfile(filename):452 raise NotFound()453 return send_file(filename, conditional=True, **options)454 94 unmodified linesmodified:flask/logging.py+2 added-1 removed
9 unmodified lines10 """11 12 from __future__ import absolute_import13 14-from logging import getLogger, StreamHandler, Formatter, Logger, DEBUG14+from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG15 16 17 def create_logger(app):18 """Creates a logger for the given application. This logger works1 unmodified line20 level based on the application's debug flag. Furthermore this21 function also removes all attached handlers in case there was a22 logger with the log name before.23 """24+ Logger = getLoggerClass()25 26 class DebugLogger(Logger):27 def getEffectiveLevel(x):28 return DEBUG if app.debug else Logger.getEffectiveLevel(x)15 unmodified linesmodified:flask/signals.py+1 added
45 unmodified lines46 # 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')50+request_tearing_down = _signals.signal('request-tearing-down')51 got_request_exception = _signals.signal('got-request-exception')modified:flask/wrappers.py+7 added-1 removed
79 unmodified lines80 """81 if __debug__:82 _assert_have_json()83 if self.mimetype == 'application/json':84+ request_charset = self.mimetype_params.get('charset')85+ if request_charset is not None:86+ j = json.loads(self.data, encoding=request_charset )87+ else:84- return json.loads(self.data)88+ j = json.loads(self.data)89 90+ return j91 92+93 class Response(ResponseBase):94 """The response object that is used by default in Flask. Works like the95 response object from Werkzeug but is set to have an HTML mimetype by96 default. Quite often you don't have to create this object yourself because6 unmodified linesmodified:tests/flask_tests.py+45 added-33 removed
413 unmodified lines414 rv = app.test_client().get('/').data415 assert 'after' in evts416 assert rv == 'request|after'417 418- def test_after_request_errors(self):419- app = flask.Flask(__name__)420- called = []421- @app.after_request422- def after_request(response):423- called.append(True)424- return response425- @app.route('/')426- def fails():427- 1/0428- rv = app.test_client().get('/')429- assert rv.status_code == 500430- assert 'Internal Server Error' in rv.data431- assert len(called) == 1432-433- def test_after_request_handler_error(self):434- called = []435- app = flask.Flask(__name__)436- @app.after_request437- def after_request(response):438- called.append(True)439- 1/0440- return response441- @app.route('/')442- def fails():443- 1/0444- rv = app.test_client().get('/')445- assert rv.status_code == 500446- assert 'Internal Server Error' in rv.data447- assert len(called) == 1448-418 def test_teardown_request_handler(self):419 called = []420 app = flask.Flask(__name__)421 @app.teardown_request23 unmodified lines445 assert rv.status_code == 200446 assert 'Response' in rv.data447 assert len(called) == 1448 480-449 def test_teardown_request_handler_error(self):450 called = []451 app = flask.Flask(__name__)452 @app.teardown_request25 unmodified lines478 assert rv.status_code == 500479 assert 'Internal Server Error' in rv.data480 assert len(called) == 2481 514-482 def test_before_after_request_order(self):483 called = []484 app = flask.Flask(__name__)485 @app.before_request44 unmodified lines530 rv = c.get('/error')531 assert rv.status_code == 500532 assert 'internal server error' == rv.data533 534+ def test_teardown_on_pop(self):535+ buffer = []536+ app = flask.Flask(__name__)537+ @app.teardown_request538+ def end_of_request(exception):539+ buffer.append(exception)540+541+ ctx = app.test_request_context()542+ ctx.push()543+ assert buffer == []544+ ctx.pop()545+ assert buffer == [None]546+547 def test_response_creation(self):548 app = flask.Flask(__name__)549 @app.route('/unicode')550 def from_unicode():87 unmodified lines638 app = flask.Flask(__name__)639 app.config.update(640 SERVER_NAME='localhost.localdomain:5000'641 )642+643 @app.route('/')644 def index():645 return None646 131 unmodified lines778 t = Thread(target=apprunner, args=(config_key,))779 t.start()780 t.join()781 782+ def test_max_content_length(self):783+ app = flask.Flask(__name__)784+ app.config['MAX_CONTENT_LENGTH'] = 64785+ @app.before_request786+ def always_first():787+ flask.request.form['myfile']788+ assert False789+ @app.route('/accept', methods=['POST'])790+ def accept_file():791+ flask.request.form['myfile']792+ assert False793+ @app.errorhandler(413)794+ def catcher(error):795+ return '42'796 797+ c = app.test_client()798+ rv = c.post('/accept', data={'myfile': 'foo' * 100})799+ assert rv.data == '42'800+801+802 class JSONTestCase(unittest.TestCase):803 804+ def test_json_body_encoding(self):805+ app = flask.Flask(__name__)806+ app.debug = True807+ @app.route('/')808+ def index():809+ return flask.request.json810+811+ c = app.test_client()812+ resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),813+ content_type='application/json; charset=iso-8859-15')814+ assert resp.data == u'Hällo Wörld'.encode('utf-8')815+816 def test_jsonify(self):817 d = dict(a=23, b=42, c=[1, 2, 3])818 app = flask.Flask(__name__)819 @app.route('/kw')829 unmodified linesmodified:CHANGES+9 added-1 removed
36 unmodified lines37 was incorrectly introduced in 0.6.38 - Added `create_jinja_loader` to override the loader creation process.39 - Implemented a silent flag for `config.from_pyfile`.40 - Added `teardown_request` decorator, for functions that should run at the end41- of a request regardless of whether an exception occurred.41+ of a request regardless of whether an exception occurred. Also the behavior42+ for `after_request` was changed. It's now no longer executed when an exception43+ is raised. See :ref:`upgrading-to-new-teardown-handling`44 - Implemented :func:`flask.has_request_context`45 - Deprecated `init_jinja_globals`. Override the46 :meth:`~flask.Flask.create_jinja_environment` method instead to47 achieve the same functionality.48+- Added :func:`safe_join`49+- The automatic JSON request data unpacking now looks at the charset50+ mimetype parameter.51+- Don't modify the session on :func:`flask.get_flashed_messages` if there52+ are no messages in the session.53+- `before_request` handlers are now able to abort requests with errors.54 55 Version 0.6.156 -------------57 159 unmodified lines