reqcontext.rst
This file
Path
docs/reqcontext.rst
239 lines · 9.7 KiB
Last changed by
Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
History of this fileTake it
The walk stopped after 200 commits: lines older than 92c7bdd point at it.
Documented Request.headersArmin Ronacherbefore adoption92c7bdd
lines 1–133why, one step back1.. _request-context:23The Request Context4===================56This document describes the behavior in Flask 0.7 which is mostly in line7with the old behavior but has some small, subtle differences.89One of the design ideas behind Flask is that there are two different10“states” in which code is executed. The application setup state in which11the application implicitly is on the module level. It starts when the12:class:`Flask` object is instantiated, and it implicitly ends when the13first request comes in. While the application is in this state a few14assumptions are true:1516- 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.2122On the contrast, during request handling, a couple of other rules exist:2324- 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.2728The magic that makes this works is internally referred in Flask as the29“request context”.3031Diving into Context Locals32--------------------------3334Say you have a utility function that returns the URL the user should be35redirected to. Imagine it would always redirect to the URL's ``next``36parameter or the HTTP referrer or the index page::3738 from flask import request, url_for3940 def redirect_url():41 return request.args.get('next') or \42 request.referrer or \43 url_for('index')4445As you can see, it accesses the request object. If you try to run this46from a plain Python shell, this is the exception you will see:4748>>> redirect_url()49Traceback (most recent call last):50 File "<stdin>", line 1, in <module>51AttributeError: 'NoneType' object has no attribute 'request'5253That makes a lot of sense because we currently do not have a request we54could access. So we have to make a request and bind it to the current55context. The :attr:`~flask.Flask.test_request_context` method can create56us a :class:`~flask.ctx.RequestContext`:5758>>> ctx = app.test_request_context('/?next=http://example.com/')5960This context can be used in two ways. Either with the `with` statement61or by calling the :meth:`~flask.ctx.RequestContext.push` and62:meth:`~flask.ctx.RequestContext.pop` methods:6364>>> ctx.push()6566From that point onwards you can work with the request object:6768>>> redirect_url()69u'http://example.com/'7071Until you call `pop`:7273>>> ctx.pop()7475Because the request context is internally maintained as a stack you can76push and pop multiple times. This is very handy to implement things like77internal redirects.7879For more information of how to utilize the request context from the80interactive Python shell, head over to the :ref:`shell` chapter.8182How the Context Works83---------------------8485If you look into how the Flask WSGI application internally works, you will86find a piece of code that looks very much like this::8788 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)9596The method :meth:`~Flask.request_context` returns a new97:class:`~flask.ctx.RequestContext` object and uses it in combination with98the `with` statement to bind the context. Everything that is called from99the same thread from this point onwards until the end of the `with`100statement will have access to the request globals (:data:`flask.request`101and others).102103The request context internally works like a stack: The topmost level on104the stack is the current active request.105:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on106the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the107stack again. On popping the application's108:func:`~flask.Flask.teardown_request` functions are also executed.109110.. _callbacks-and-errors:111112Callbacks and Errors113--------------------114115What happens if an error occurs in Flask during request processing? This116particular behavior changed in 0.7 because we wanted to make it easier to117understand what is actually happening. The new behavior is quite simple:1181191. 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.1231242. 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.1271283. 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.1311324. At the end of the request the :meth:`~flask.Flask.teardown_request`133 functions are executed. This always happens, even in case of anUpdated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
lines 134–136why, one step back134 unhandled exception down the road or if a before-request handler was135 not executed yet or at all (for example in test environments sometimes136 you might want to not execute before-request callbacks).Documented Request.headersArmin Ronacherbefore adoption92c7bdd
lines 137–186why, one step back137138Now what happens on errors? In production mode if an exception is not139caught, the 500 internal server handler is called. In development mode140however the exception is not further processed and bubbles up to the WSGI141server. That way things like the interactive debugger can provide helpful142debug information.143144An important change in 0.7 is that the internal server error is now no145longer post processed by the after request callbacks and after request146callbacks are no longer guaranteed to be executed. This way the internal147dispatching code looks cleaner and is easier to customize and understand.148149The new teardown functions are supposed to be used as a replacement for150things that absolutely need to happen at the end of request.151152Teardown Callbacks153------------------154155The teardown callbacks are special callbacks in that they are executed at156at different point. Strictly speaking they are independent of the actual157request handling as they are bound to the lifecycle of the158:class:`~flask.ctx.RequestContext` object. When the request context is159popped, the :meth:`~flask.Flask.teardown_request` functions are called.160161This is important to know if the life of the request context is prolonged162by using the test client in a with statement or when using the request163context from the command line::164165 with app.test_client() as client:166 resp = client.get('/foo')167 # the teardown functions are still not called at that point168 # even though the response ended and you have the response169 # object in your hand170171 # only when the code reaches this point the teardown functions172 # are called. Alternatively the same thing happens if another173 # request was triggered from the test client174175It's easy to see the behavior from the command line:176177>>> app = Flask(__name__)178>>> @app.teardown_request179... def teardown_request(exception=None):180... print 'this runs after request'181...182>>> ctx = app.test_request_context()183>>> ctx.push()184>>> ctx.pop()185this runs after request186>>>Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
lines 187–192why, one step back187188Keep in mind that teardown callbacks are always executed, even if189before-request callbacks were not executed yet but an exception happened.190Certain parts of the test system might also temporarily create a request191context without calling the before-request handlers. Make sure to write192your teardown-request handlers in a way that they will never fail.Documented Request.headersArmin Ronacherbefore adoption92c7bdd
lines 193–239why, one step back193194.. _notes-on-proxies:195196Notes On Proxies197----------------198199Some of the objects provided by Flask are proxies to other objects. The200reason behind this is that these proxies are shared between threads and201they have to dispatch to the actual object bound to a thread behind the202scenes as necessary.203204Most of the time you don't have to care about that, but there are some205exceptions where it is good to know that this object is an actual proxy:206207- The proxy objects do not fake their inherited types, so if you want to208 perform actual instance checks, you have to do that on the instance209 that is being proxied (see `_get_current_object` below).210- if the object reference is important (so for example for sending211 :ref:`signals`)212213If you need to get access to the underlying object that is proxied, you214can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::215216 app = current_app._get_current_object()217 my_signal.send(app)218219Context Preservation on Error220-----------------------------221222If an error occurs or not, at the end of the request the request context223is popped and all data associated with it is destroyed. During224development however that can be problematic as you might want to have the225information around for a longer time in case an exception occurred. In226Flask 0.6 and earlier in debug mode, if an exception occurred, the227request context was not popped so that the interactive debugger can still228provide you with important information.229230Starting with Flask 0.7 you have finer control over that behavior by231setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By232default it's linked to the setting of ``DEBUG``. If the application is in233debug mode the context is preserved, in production mode it's not.234235Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode236as it will cause your application to leak memory on exceptions. However237it can be useful during development to get the same error preserving238behavior as in development mode when attempting to debug an error that239only occurs under production settings.