The Request Context

The request context keeps track of the request-level data during arequest. Rather than passing the request object to each function thatruns during a request, the request and session proxiesare accessed instead.

This is similar to the The Application Context, which keeps track of theapplication-level data independent of a request. A correspondingapplication context is pushed when a request context is pushed.

Purpose of the Context

When the Flask application handles a request, it creates aRequest object based on the environment it received from theWSGI server. Because a worker (thread, process, or coroutine dependingon the server) handles only one request at a time, the request data canbe considered global to that worker during that request. Flask uses theterm context local for this.

Flask automatically pushes a request context when handling a request.View functions, error handlers, and other functions that run during arequest will have access to the request proxy, which points tothe request object for the current request.

Lifetime of the Context

When a Flask application begins handling a request, it pushes a requestcontext, which also pushes an The Application Context. When the request endsit pops the request context then the application context.

The context is unique to each thread (or other worker type).request cannot be passed to another thread, the other threadwill have a different context stack and will not know about the requestthe parent thread was pointing to.

Context locals are implemented in Werkzeug. See Context Localsfor more information on how this works internally.

Manually Push a Context

If you try to access request, or anything that uses it, outsidea request context, you’ll get this error message:

  1. RuntimeError: Working outside of request context.
  2.  
  3. This typically means that you attempted to use functionality that
  4. needed an active HTTP request. Consult the documentation on testing
  5. for information about how to avoid this problem.

This should typically only happen when testing code that expects anactive request. One option is to use thetest client to simulate a full request. Oryou can use test_request_context() in a with block, andeverything that runs in the block will have access to request,populated with your test data.

  1. def generate_report(year):
  2. format = request.args.get('format')
  3. ...
  4.  
  5. with app.test_request_context(
  6. '/make_report/2017', data={'format': 'short'}):
  7. generate_report()

If you see that error somewhere else in your code not related totesting, it most likely indicates that you should move that code into aview function.

For information on how to use the request context from the interactivePython shell, see Working with the Shell.

How the Context Works

The Flask.wsgi_app() method is called to handle each request. Itmanages the contexts during the request. Internally, the request andapplication contexts work as stacks, _request_ctx_stack and_app_ctx_stack. When contexts are pushed onto the stack, theproxies that depend on them are available and point at information fromthe top context on the stack.

When the request starts, a RequestContext is created andpushed, which creates and pushes an AppContext first ifa context for that application is not already the top context. Whilethese contexts are pushed, the current_app, g,request, and session proxies are available to theoriginal thread handling the request.

Because the contexts are stacks, other contexts may be pushed to changethe proxies during a request. While this is not a common pattern, itcan be used in advanced applications to, for example, do internalredirects or chain different applications together.

After the request is dispatched and a response is generated and sent,the request context is popped, which then pops the application context.Immediately before they are popped, the teardown_request()and teardown_appcontext() functions are are executed. Theseexecute even if an unhandled exception occurred during dispatch.

Callbacks and Errors

Flask dispatches a request in multiple stages which can affect therequest, response, and how errors are handled. The contexts are activeduring all of these stages.

A Blueprint can add handlers for these events that are specificto the blueprint. The handlers for a blueprint will run if the blueprintowns the route that matches the request.

  • Before each request, before_request() functions arecalled. If one of these functions return a value, the otherfunctions are skipped. The return value is treated as the responseand the view function is not called.

  • If the before_request() functions did not return aresponse, the view function for the matched route is called andreturns a response.

  • The return value of the view is converted into an actual responseobject and passed to the after_request()functions. Each function returns a modified or new response object.

  • After the response is returned, the contexts are popped, which callsthe teardown_request() andteardown_appcontext() functions. These functions arecalled even if an unhandled exception was raised at any point above.

If an exception is raised before the teardown functions, Flask tries tomatch it with an errorhandler() function to handle theexception and return a response. If no error handler is found, or thehandler itself raises an exception, Flask returns a generic500 Internal Server Error response. The teardown functions are stillcalled, and are passed the exception object.

If debug mode is enabled, unhandled exceptions are not converted to a500 response and instead are propagated to the WSGI server. Thisallows the development server to present the interactive debugger withthe traceback.

Teardown Callbacks

The teardown callbacks are independent of the request dispatch, and areinstead called by the contexts when they are popped. The functions arecalled even if there is an unhandled exception during dispatch, and formanually pushed contexts. This means there is no guarantee that anyother parts of the request dispatch have run first. Be sure to writethese functions in a way that does not depend on other callbacks andwill not fail.

During testing, it can be useful to defer popping the contexts after therequest ends, so that their data can be accessed in the test function.Using the test_client() as a with block to preserve thecontexts until the with block exits.

  1. from flask import Flask, request
  2.  
  3. app = Flask(__name__)
  4.  
  5. @app.route('/')
  6. def hello():
  7. print('during view')
  8. return 'Hello, World!'
  9.  
  10. @app.teardown_request
  11. def show_teardown(exception):
  12. print('after with block')
  13.  
  14. with app.test_request_context():
  15. print('during with block')
  16.  
  17. # teardown functions are called after the context with block exits
  18.  
  19. with app.test_client() as client:
  20. client.get('/')
  21. # the contexts are not popped even though the request ended
  22. print(request.path)
  23.  
  24. # the contexts are popped and teardown functions are called after
  25. # the client with block exists

Signals

If signals_available is true, the following signals aresent:

Context Preservation on Error

At the end of a request, the request context is popped and all dataassociated with it is destroyed. If an error occurs during development,it is useful to delay destroying the data for debugging purposes.

When the development server is running in development mode (theFLASK_ENV environment variable is set to 'development'), theerror and data will be preserved and shown in the interactive debugger.

This behavior can be controlled with thePRESERVE_CONTEXT_ON_EXCEPTION config. As described above, itdefaults to True in the development environment.

Do not enable PRESERVE_CONTEXT_ON_EXCEPTION in production, as itwill cause your application to leak memory on exceptions.

Notes On Proxies

Some of the objects provided by Flask are proxies to other objects. Theproxies are accessed in the same way for each worker thread, butpoint to the unique object bound to each worker behind the scenes asdescribed on this page.

Most of the time you don’t have to care about that, but there are someexceptions where it is good to know that this object is an actual proxy:

  • The proxy objects cannot fake their type as the actual object types.If you want to perform instance checks, you have to do that on theobject being proxied.

  • If the specific object reference is important, for example forsending Signals or passing data to a background thread.

If you need to access the underlying object that is proxied, use the_get_current_object() method:

  1. app = current_app._get_current_object()
  2. my_signal.send(app)