Skip to content
Myr

reqcontext.rst

This file

Path

docs/reqcontext.rst

223 lines · 9.0 KiB

Last changed by

Fix typo s/at at/at a/Daniel Neuhäuserbefore adoption5689ef3

History of this file

Take it

The walk stopped after 200 commits: lines older than 3fdcefb point at it.

Merge pull request #625 from soulseekah/masterKenneth Reitzbefore adoption3fdcefb

lines 1–139why, one step back
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.89It is recommended that you read the :ref:`app-context` chapter first.1011Diving into Context Locals12--------------------------1314Say you have a utility function that returns the URL the user should be15redirected to. Imagine it would always redirect to the URL's ``next``16parameter or the HTTP referrer or the index page::1718 from flask import request, url_for1920 def redirect_url():21 return request.args.get('next') or \22 request.referrer or \23 url_for('index')2425As you can see, it accesses the request object. If you try to run this26from a plain Python shell, this is the exception you will see:2728>>> redirect_url()29Traceback (most recent call last):30 File "<stdin>", line 1, in <module>31AttributeError: 'NoneType' object has no attribute 'request'3233That makes a lot of sense because we currently do not have a request we34could access. So we have to make a request and bind it to the current35context. The :attr:`~flask.Flask.test_request_context` method can create36us a :class:`~flask.ctx.RequestContext`:3738>>> ctx = app.test_request_context('/?next=http://example.com/')3940This context can be used in two ways. Either with the `with` statement41or by calling the :meth:`~flask.ctx.RequestContext.push` and42:meth:`~flask.ctx.RequestContext.pop` methods:4344>>> ctx.push()4546From that point onwards you can work with the request object:4748>>> redirect_url()49u'http://example.com/'5051Until you call `pop`:5253>>> ctx.pop()5455Because the request context is internally maintained as a stack you can56push and pop multiple times. This is very handy to implement things like57internal redirects.5859For more information of how to utilize the request context from the60interactive Python shell, head over to the :ref:`shell` chapter.6162How the Context Works63---------------------6465If you look into how the Flask WSGI application internally works, you will66find a piece of code that looks very much like this::6768 def wsgi_app(self, environ):69 with self.request_context(environ):70 try:71 response = self.full_dispatch_request()72 except Exception, e:73 response = self.make_response(self.handle_exception(e))74 return response(environ, start_response)7576The method :meth:`~Flask.request_context` returns a new77:class:`~flask.ctx.RequestContext` object and uses it in combination with78the `with` statement to bind the context. Everything that is called from79the same thread from this point onwards until the end of the `with`80statement will have access to the request globals (:data:`flask.request`81and others).8283The request context internally works like a stack: The topmost level on84the stack is the current active request.85:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on86the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the87stack again. On popping the application's88:func:`~flask.Flask.teardown_request` functions are also executed.8990Another thing of note is that the request context will automatically also91create an :ref:`application context <app-context>` when it's pushed and92there is no application context for that application so far.9394.. _callbacks-and-errors:9596Callbacks and Errors97--------------------9899What happens if an error occurs in Flask during request processing? This100particular behavior changed in 0.7 because we wanted to make it easier to101understand what is actually happening. The new behavior is quite simple:1021031. Before each request, :meth:`~flask.Flask.before_request` functions are104 executed. If one of these functions return a response, the other105 functions are no longer called. In any case however the return value106 is treated as a replacement for the view's return value.1071082. If the :meth:`~flask.Flask.before_request` functions did not return a109 response, the regular request handling kicks in and the view function110 that was matched has the chance to return a response.1111123. The return value of the view is then converted into an actual response113 object and handed over to the :meth:`~flask.Flask.after_request`114 functions which have the chance to replace it or modify it in place.1151164. At the end of the request the :meth:`~flask.Flask.teardown_request`117 functions are executed. This always happens, even in case of an118 unhandled exception down the road or if a before-request handler was119 not executed yet or at all (for example in test environments sometimes120 you might want to not execute before-request callbacks).121122Now what happens on errors? In production mode if an exception is not123caught, the 500 internal server handler is called. In development mode124however the exception is not further processed and bubbles up to the WSGI125server. That way things like the interactive debugger can provide helpful126debug information.127128An important change in 0.7 is that the internal server error is now no129longer post processed by the after request callbacks and after request130callbacks are no longer guaranteed to be executed. This way the internal131dispatching code looks cleaner and is easier to customize and understand.132133The new teardown functions are supposed to be used as a replacement for134things that absolutely need to happen at the end of request.135136Teardown Callbacks137------------------138139The teardown callbacks are special callbacks in that they are executed at

Fix typo s/at at/at a/Daniel Neuhäuserbefore adoption5689ef3

line 140why, one step back
140a different point. Strictly speaking they are independent of the actual

Merge pull request #625 from soulseekah/masterKenneth Reitzbefore adoption3fdcefb

lines 141–223why, one step back
141request handling as they are bound to the lifecycle of the
142:class:`~flask.ctx.RequestContext` object. When the request context is143popped, the :meth:`~flask.Flask.teardown_request` functions are called.144145This is important to know if the life of the request context is prolonged146by using the test client in a with statement or when using the request147context from the command line::148149 with app.test_client() as client:150 resp = client.get('/foo')151 # the teardown functions are still not called at that point152 # even though the response ended and you have the response153 # object in your hand154155 # only when the code reaches this point the teardown functions156 # are called. Alternatively the same thing happens if another157 # request was triggered from the test client158159It's easy to see the behavior from the command line:160161>>> app = Flask(__name__)162>>> @app.teardown_request163... def teardown_request(exception=None):164... print 'this runs after request'165...166>>> ctx = app.test_request_context()167>>> ctx.push()168>>> ctx.pop()169this runs after request170>>>171172Keep in mind that teardown callbacks are always executed, even if173before-request callbacks were not executed yet but an exception happened.174Certain parts of the test system might also temporarily create a request175context without calling the before-request handlers. Make sure to write176your teardown-request handlers in a way that they will never fail.177178.. _notes-on-proxies:179180Notes On Proxies181----------------182183Some of the objects provided by Flask are proxies to other objects. The184reason behind this is that these proxies are shared between threads and185they have to dispatch to the actual object bound to a thread behind the186scenes as necessary.187188Most of the time you don't have to care about that, but there are some189exceptions where it is good to know that this object is an actual proxy:190191- The proxy objects do not fake their inherited types, so if you want to192 perform actual instance checks, you have to do that on the instance193 that is being proxied (see `_get_current_object` below).194- if the object reference is important (so for example for sending195 :ref:`signals`)196197If you need to get access to the underlying object that is proxied, you198can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::199200 app = current_app._get_current_object()201 my_signal.send(app)202203Context Preservation on Error204-----------------------------205206If an error occurs or not, at the end of the request the request context207is popped and all data associated with it is destroyed. During208development however that can be problematic as you might want to have the209information around for a longer time in case an exception occurred. In210Flask 0.6 and earlier in debug mode, if an exception occurred, the211request context was not popped so that the interactive debugger can still212provide you with important information.213214Starting with Flask 0.7 you have finer control over that behavior by215setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216default it's linked to the setting of ``DEBUG``. If the application is in217debug mode the context is preserved, in production mode it's not.218219Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode220as it will cause your application to leak memory on exceptions. However221it can be useful during development to get the same error preserving222behavior as in development mode when attempting to debug an error that223only occurs under production settings.