reqcontext.rst
This file
Path
docs/reqcontext.rst
231 lines · 9.2 KiB
Last changed by
Merge branch 'blueprints' of github.com:mitsuhiko/flask into blueprintsArmin Ronacherbefore adoption5ca333e
History of this fileTake it
1.. _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 an134 unhandled exception down the road.135136Now what happens on errors? In production mode if an exception is not137caught, the 500 internal server handler is called. In development mode138however the exception is not further processed and bubbles up to the WSGI139server. That way things like the interactive debugger can provide helpful140debug information.141142An important change in 0.7 is that the internal server error is now no143longer post processed by the after request callbacks and after request144callbacks are no longer guaranteed to be executed. This way the internal145dispatching code looks cleaner and is easier to customize and understand.146147The new teardown functions are supposed to be used as a replacement for148things that absolutely need to happen at the end of request.149150Teardown Callbacks151------------------152153The teardown callbacks are special callbacks in that they are executed at154at different point. Strictly speaking they are independent of the actual155request handling as they are bound to the lifecycle of the156:class:`~flask.ctx.RequestContext` object. When the request context is157popped, the :meth:`~flask.Flask.teardown_request` functions are called.158159This is important to know if the life of the request context is prolonged160by using the test client in a with statement of when using the request161context from the command line::162163 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 hand168169 # 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 client172173It's easy to see the behavior from the command line:174175>>> app = Flask(__name__)176>>> @app.teardown_request177... def teardown_request(exception=None):178... print 'this runs after request'179...180>>> ctx = app.test_request_context()181>>> ctx.push()182>>> ctx.pop()183this runs after request184>>>185186.. _notes-on-proxies:187188Notes On Proxies189----------------190191Some of the objects provided by Flask are proxies to other objects. The192reason behind this is that these proxies are shared between threads and193they have to dispatch to the actual object bound to a thread behind the194scenes as necessary.195196Most of the time you don't have to care about that, but there are some197exceptions where it is good to know that this object is an actual proxy:198199- The proxy objects do not fake their inherited types, so if you want to200 perform actual instance checks, you have to do that on the instance201 that is being proxied (see `_get_current_object` below).202- if the object reference is important (so for example for sending203 :ref:`signals`)204205If you need to get access to the underlying object that is proxied, you206can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::207208 app = current_app._get_current_object()209 my_signal.send(app)210211Context Preservation on Error212-----------------------------213214If an error occurs or not, at the end of the request the request context215is popped and all data associated with it is destroyed. During216development however that can be problematic as you might want to have the217information around for a longer time in case an exception occurred. In218Flask 0.6 and earlier in debug mode, if an exception occurred, the219request context was not popped so that the interactive debugger can still220provide you with important information.221222Starting with Flask 0.7 you have finer control over that behavior by223setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By224default it's linked to the setting of ``DEBUG``. If the application is in225debug mode the context is preserved, in production mode it's not.226227Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode228as it will cause your application to leak memory on exceptions. However229it can be useful during development to get the same error preserving230behavior as in development mode when attempting to debug an error that231only occurs under production settings.