Skip to content
Myr

Merge pull request #2685 from davidism/app-context-docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

rework context docs

authored by David Lord · committed by GitHub · parents 47a0086, 2411707 · Browse files · 7 files+531 added−364 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+531 added−364 removed

  • other:+531 added−364 removed

7 files+531 added−364 removed

modified:docs/api.rst+47 added-46 removed
209 unmodified lines
210thing, like it does for :class:`request` and :class:`session`.211212.. data:: g213214 Just store on this whatever you want. For example a database215 connection or the user that is currently logged in.214 A namespace object that can store data during an215 :doc:`application context </appcontext>`. This is an instance of216 :attr:`Flask.app_ctx_globals_class`, which defaults to217 :class:`ctx._AppCtxGlobals`.218217 Starting with Flask 0.10 this is stored on the application context and218 no longer on the request context which means it becomes available if219 only the application context is bound and not yet a request. This220 is especially useful when combined with the :ref:`faking-resources`221 pattern for testing.219 This is a good place to store resources during a request. During220 testing, you can use the :ref:`faking-resources` pattern to221 pre-configure such resources.222223 Additionally as of 0.10 you can use the :meth:`get` method to224 get an attribute or ``None`` (or the second argument) if it's not set.225 These two usages are now equivalent::223 This is a proxy. See :ref:`notes-on-proxies` for more information.224227 user = getattr(flask.g, 'user', None)228 user = flask.g.get('user', None)225 .. versionchanged:: 0.10226 Bound to the application context instead of the request context.227230 It's now also possible to use the ``in`` operator on it to see if an231 attribute is defined and it yields all keys on iteration.228.. autoclass:: flask.ctx._AppCtxGlobals229 :members:230233 As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same234 way you would use them on a dictionary.231236 This is a proxy. See :ref:`notes-on-proxies` for more information.237238232Useful Functions and Classes233----------------------------234235.. data:: current_app236244 Points to the application handling the request. This is useful for245 extensions that want to support multiple applications running side246 by side. This is powered by the application context and not by the247 request context, so you can change the value of this proxy by248 using the :meth:`~flask.Flask.app_context` method.237 A proxy to the application handling the current request. This is238 useful to access the application without needing to import it, or if239 it can't be imported, such as when using the application factory240 pattern or in blueprints and extensions.241250 This is a proxy. See :ref:`notes-on-proxies` for more information.242 This is only available when an243 :doc:`application context </appcontext>` is pushed. This happens244 automatically during requests and CLI commands. It can be controlled245 manually with :meth:`~flask.Flask.app_context`.246247 This is a proxy. See :ref:`notes-on-proxies` for more information.248249.. autofunction:: has_request_context250251.. autofunction:: copy_current_request_context252
127 unmodified lines
380 :members:381382.. data:: _request_ctx_stack383387 The internal :class:`~werkzeug.local.LocalStack` that is used to implement388 all the context local objects used in Flask. This is a documented389 instance and can be used by extensions and application code but the390 use is discouraged in general.384 The internal :class:`~werkzeug.local.LocalStack` that holds385 :class:`~flask.ctx.RequestContext` instances. Typically, the386 :data:`request` and :data:`session` proxies should be accessed387 instead of the stack. It may be useful to access the stack in388 extension code.389392 The following attributes are always present on each layer of the393 stack:390 The following attributes are always present on each layer of the391 stack:392395 `app`393 `app`394 the active Flask application.395398 `url_adapter`396 `url_adapter`397 the URL adapter that was used to match the request.398401 `request`399 `request`400 the current request object.401404 `session`402 `session`403 the active session object.404407 `g`405 `g`406 an object with all the attributes of the :data:`flask.g` object.407410 `flashes`408 `flashes`409 an internal cache for the flashed messages.410413 Example usage::411 Example usage::412415 from flask import _request_ctx_stack413 from flask import _request_ctx_stack414417 def get_session():418 ctx = _request_ctx_stack.top419 if ctx is not None:420 return ctx.session415 def get_session():416 ctx = _request_ctx_stack.top417 if ctx is not None:418 return ctx.session419420.. autoclass:: flask.ctx.AppContext421 :members:422423.. data:: _app_ctx_stack424427 Works similar to the request context but only binds the application.428 This is mainly there for extensions to store data.425 The internal :class:`~werkzeug.local.LocalStack` that holds426 :class:`~flask.ctx.AppContext` instances. Typically, the427 :data:`current_app` and :data:`g` proxies should be accessed instead428 of the stack. Extensions can access the contexts on the stack as a429 namespace to store data.430430 .. versionadded:: 0.9431 .. versionadded:: 0.9432433.. autoclass:: flask.blueprints.BlueprintSetupState434 :members:435
387 unmodified lines
modified:docs/appcontext.rst+113 added-98 removed
1.. currentmodule:: flask23.. _app-context:45The Application Context6=======================76.. versionadded:: 0.98The application context keeps track of the application-level data during9a request, CLI command, or other activity. Rather than passing the10application around to each function, the :data:`current_app` and11:data:`g` proxies are accessed instead.128One of the design ideas behind Flask is that there are at least two9different “states” in which code is executed:13This is similar to the :doc:`/reqcontext`, which keeps track of14request-level data during a request. A corresponding application context15is pushed when a request context is pushed.16111. The application setup state, in which the application implicitly is12on the module level.17Purpose of the Context18----------------------1914 This state starts when the :class:`Flask` object is instantiated, and15 it implicitly ends when the first request comes in. While the16 application is in this state, a few assumptions are true:20The :class:`Flask` application object has attributes, such as21:attr:`~Flask.config`, that are useful to access within views and22:doc:`CLI commands </cli>`. However, importing the ``app`` instance23within the modules in your project is prone to circular import issues.24When using the :doc:`app factory pattern </patterns/appfactories>` or25writing reusable :doc:`blueprints </blueprints>` or26:doc:`extensions </extensions>` there won't be an ``app`` instance to27import at all.2818 - the programmer can modify the application object safely.19 - no request handling happened so far20 - you have to have a reference to the application object in order to21 modify it, there is no magic proxy that can give you a reference to22 the application object you're currently creating or modifying.29Flask solves this issue with the *application context*. Rather than30referring to an ``app`` directly, you use the the :data:`current_app`31proxy, which points to the application handling the current activity.32242. In contrast, in the request handling state, a couple of other rules25exist:33Flask automatically *pushes* an application context when handling a34request. View functions, error handlers, and other functions that run35during a request will have access to :data:`current_app`.3627 - while a request is active, the context local objects28 (:data:`flask.request` and others) point to the current request.29 - any code can get hold of these objects at any time.37Flask will also automatically push an app context when running CLI38commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.39313. There is also a third state somewhere in between 'module-level' and32'request-handling':4034 Sometimes you are dealing with an application in a way that is similar to35 how you interact with applications during request handling, but without36 there being an active request. Consider, for instance, that you're37 sitting in an interactive Python shell and interacting with the38 application, or a command line application.41Lifetime of the Context42-----------------------4340The application context is what powers the :data:`~flask.current_app`41context local.44The application context is created and destroyed as necessary. When a45Flask application begins handling a request, it pushes an application46context and a :doc:`request context </reqcontext>`. When the request47ends it pops the request context then the application context.48Typically, an application context will have the same lifetime as a49request.5043Purpose of the Application Context44----------------------------------51See :doc:`/reqcontext` for more information about how the contexts work52and the full lifecycle of a request.5346The main reason for the application's context existence is that in the47past a bunch of functionality was attached to the request context for lack48of a better solution. Since one of the pillars of Flask's design is that49you can have more than one application in the same Python process.5451So how does the code find the “right” application? In the past we52recommended passing applications around explicitly, but that caused issues53with libraries that were not designed with that in mind.55Manually Push a Context56-----------------------5755A common workaround for that problem was to use the56:data:`~flask.current_app` proxy later on, which was bound to the current57request's application reference. Since creating such a request context is58an unnecessarily expensive operation in case there is no request around,59the application context was introduced.58If you try to access :data:`current_app`, or anything that uses it,59outside an application context, you'll get this error message:6061Creating an Application Context62-------------------------------61.. code-block:: pytb6264There are two ways to make an application context. The first one is65implicit: whenever a request context is pushed, an application context66will be created alongside if this is necessary. As a result, you can67ignore the existence of the application context unless you need it.63 RuntimeError: Working outside of application context.6469The second way is the explicit way using the70:meth:`~flask.Flask.app_context` method::65 This typically means that you attempted to use functionality that66 needed to interface with the current application object in some way.67 To solve this, set up an application context with app.app_context().6872 from flask import Flask, current_app69If you see that error while configuring your application, such as when70initializing an extension, you can push a context manually since you71have direct access to the ``app``. Use :meth:`~Flask.app_context` in a72``with`` block, and everything that runs in the block will have access73to :data:`current_app`. ::7474 app = Flask(__name__)75 with app.app_context():76 # within this block, current_app points to app.77 print current_app.name75 def create_app():76 app = Flask(__name__)7779The application context is also used by the :func:`~flask.url_for`80function in case a ``SERVER_NAME`` was configured. This allows you to81generate URLs even in the absence of a request.78 with app.app_context():79 init_db()8083If no request context has been pushed and an application context has84not been explicitly set, a ``RuntimeError`` will be raised. ::81 return app8286 RuntimeError: Working outside of application context.83If you see that error somewhere else in your code not related to84configuring the application, it most likely indicates that you should85move that code into a view function or CLI command.8688Locality of the Context89-----------------------8791The application context is created and destroyed as necessary. It never92moves between threads and it will not be shared between requests. As such93it is the perfect place to store database connection information and other94things. The internal stack object is called :data:`flask._app_ctx_stack`.95Extensions are free to store additional information on the topmost level,96assuming they pick a sufficiently unique name and should put their97information there, instead of on the :data:`flask.g` object which is reserved98for user code.88Storing Data89------------90100For more information about that, see :ref:`extension-dev`.91The application context is a good place to store common data during a92request or CLI command. Flask provides the :data:`g object <g>` for this93purpose. It is a simple namespace object that has the same lifetime as94an application context.95102Context Usage103-------------96.. note::97 The ``g`` name stands for "global", but that is referring to the98 data being global *within a context*. The data on ``g`` is lost99 after the context ends, and it is not an appropriate place to store100 data between requests. Use the :data:`session` or a database to101 store data across requests.102105The context is typically used to cache resources that need to be created106on a per-request or usage case. For instance, database connections are107destined to go there. When storing things on the application context108unique names should be chosen as this is a place that is shared between109Flask applications and extensions.103A common use for :data:`g` is to manage resources during a request.104111The most common usage is to split resource management into two parts:1051. ``get_X()`` creates resource ``X`` if it does not exist, caching it106 as ``g.X``.1072. ``teardown_X()`` closes or otherwise deallocates the resource if it108 exists. It is registered as a :meth:`~Flask.teardown_appcontext`109 handler.1101131. an implicit resource caching on the context.1142. a context teardown based resource deallocation.111For example, you can manage a database connection using this pattern::112116Generally there would be a ``get_X()`` function that creates resource117``X`` if it does not exist yet and otherwise returns the same resource,118and a ``teardown_X()`` function that is registered as teardown handler.119120This is an example that connects to a database::121122 import sqlite3113 from flask import g114115 def get_db():126 db = getattr(g, '_database', None)127 if db is None:128 db = g._database = connect_to_database()129 return db116 if 'db' not in g:117 g.db = connect_to_database()118119 return g.db120121 @app.teardown_appcontext132 def teardown_db(exception):133 db = getattr(g, '_database', None)122 def teardown_db():123 db = g.pop('db', None)124125 if db is not None:126 db.close()127137The first time ``get_db()`` is called the connection will be established.138To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::128During a request, every call to ``get_db()`` will return the same129connection, and it will be closed automatically at the end of the130request.131132You can use :class:`~werkzeug.local.LocalProxy` to make a new context133local from ``get_db()``::134135 from werkzeug.local import LocalProxy136 db = LocalProxy(get_db)137143That way a user can directly access ``db`` which internally calls144``get_db()``.138Accessing ``db`` will call ``get_db`` internally, in the same way that139:data:`current_app` works.140141----142143If you're writing an extension, :data:`g` should be reserved for user144code. You may store internal data on the context itself, but be sure to145use a sufficiently unique name. The current context is accessed with146:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see147:doc:`extensiondev`.148149150Events and Signals151------------------152153The application will call functions registered with154:meth:`~Flask.teardown_appcontext` when the application context is155popped.156157If :data:`~signals.signals_available` is true, the following signals are158sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and159:data:`appcontext_popped`.
modified:docs/reqcontext.rst+201 added-158 removed
1.. currentmodule:: flask23.. _request-context:45The Request Context6===================76This document describes the behavior in Flask 0.7 which is mostly in line7with the old behavior but has some small, subtle differences.8The request context keeps track of the request-level data during a9request. Rather than passing the request object to each function that10runs during a request, the :data:`request` and :data:`session` proxies11are accessed instead.129It is recommended that you read the :ref:`app-context` chapter first.13This is similar to the :doc:`/appcontext`, which keeps track of the14application-level data independent of a request. A corresponding15application context is pushed when a request context is pushed.1611Diving into Context Locals12--------------------------1714Say 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::18Purpose of the Context19----------------------2018 from flask import request, url_for21When the :class:`Flask` application handles a request, it creates a22:class:`Request` object based on the environment it received from the23WSGI server. Because a *worker* (thread, process, or coroutine depending24on the server) handles only one request at a time, the request data can25be considered global to that worker during that request. Flask uses the26term *context local* for this.2720 def redirect_url():21 return request.args.get('next') or \22 request.referrer or \23 url_for('index')28Flask automatically *pushes* a request context when handling a request.29View functions, error handlers, and other functions that run during a30request will have access to the :data:`request` proxy, which points to31the request object for the current request.3225As 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:3328>>> redirect_url()29Traceback (most recent call last):30 File "<stdin>", line 1, in <module>31AttributeError: 'NoneType' object has no attribute 'request'34Lifetime of the Context35-----------------------3633That 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`:37When a Flask application begins handling a request, it pushes a request38context, which also pushes an :doc:`/appcontext`. When the request ends39it pops the request context then the application context.4038>>> ctx = app.test_request_context('/?next=http://example.com/')41The context is unique to each thread (or other worker type).42:data:`request` cannot be passed to another thread, the other thread43will have a different context stack and will not know about the request44the parent thread was pointing to.4540This 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:46Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`47for more information on how this works internally.4844>>> ctx.push()4946From that point onwards you can work with the request object:50Manually Push a Context51-----------------------5248>>> redirect_url()49u'http://example.com/'53If you try to access :data:`request`, or anything that uses it, outside54a request context, you'll get this error message:5551Until you call `pop`:56.. code-block:: pytb5753>>> ctx.pop()58 RuntimeError: Working outside of request context.5955Because the request context is internally maintained as a stack you can56push and pop multiple times. This is very handy to implement things like57internal redirects.60 This typically means that you attempted to use functionality that61 needed an active HTTP request. Consult the documentation on testing62 for information about how to avoid this problem.6359For more information of how to utilize the request context from the60interactive Python shell, head over to the :ref:`shell` chapter.64This should typically only happen when testing code that expects an65active request. One option is to use the66:meth:`test client <Flask.test_client>` to simulate a full request. Or67you can use :meth:`~Flask.test_request_context` in a ``with`` block, and68everything that runs in the block will have access to :data:`request`,69populated with your test data. ::7071 def generate_report(year):72 format = request.args.get('format')73 ...7475 with app.test_request_context(76 '/make_report/2017', data={'format': 'short'}):77 generate_report()7879If you see that error somewhere else in your code not related to80testing, it most likely indicates that you should move that code into a81view function.8283For information on how to use the request context from the interactive84Python shell, see :doc:`/shell`.858687How the Context Works88---------------------8965If you look into how the Flask WSGI application internally works, you will66find a piece of code that looks very much like this::90The :meth:`Flask.wsgi_app` method is called to handle each request. It91manages the contexts during the request. Internally, the request and92application contexts work as stacks, :data:`_request_ctx_stack` and93:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the94proxies that depend on them are available and point at information from95the top context on the stack.9668 def wsgi_app(self, environ):69 with self.request_context(environ):70 try:71 response = self.full_dispatch_request()72 except Exception as e:73 response = self.make_response(self.handle_exception(e))74 return response(environ, start_response)97When the request starts, a :class:`~ctx.RequestContext` is created and98pushed, which creates and pushes an :class:`~ctx.AppContext` first if99a context for that application is not already the top context. While100these contexts are pushed, the :data:`current_app`, :data:`g`,101:data:`request`, and :data:`session` proxies are available to the102original thread handling the request.10376The 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).104Because the contexts are stacks, other contexts may be pushed to change105the proxies during a request. While this is not a common pattern, it106can be used in advanced applications to, for example, do internal107redirects or chain different applications together.10883The 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.109After the request is dispatched and a response is generated and sent,110the request context is popped, which then pops the application context.111Immediately before they are popped, the :meth:`~Flask.teardown_request`112and :meth:`~Flask.teardown_appcontext` functions are are executed. These113execute even if an unhandled exception occurred during dispatch.11490Another 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.115116.. _callbacks-and-errors:117118Callbacks and Errors119--------------------12099What 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:121Flask dispatches a request in multiple stages which can affect the122request, response, and how errors are handled. The contexts are active123during all of these stages.1241031. 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.125A :class:`Blueprint` can add handlers for these events that are specific126to the blueprint. The handlers for a blueprint will run if the blueprint127owns the route that matches the request.1281082. 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.129#. Before each request, :meth:`~Flask.before_request` functions are130 called. If one of these functions return a value, the other131 functions are skipped. The return value is treated as the response132 and the view function is not called.1331123. 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.134#. If the :meth:`~Flask.before_request` functions did not return a135 response, the view function for the matched route is called and136 returns a response.1371164. 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).138#. The return value of the view is converted into an actual response139 object and passed to the :meth:`~Flask.after_request`140 functions. Each function returns a modified or new response object.141122Now what happens on errors? If you are not in debug mode and an exception is not 123caught, the 500 internal server handler is called. In debug mode 124however the exception is not further processed and bubbles up to the WSGI 125server. That way things like the interactive debugger can provide helpful126debug information.142#. After the response is returned, the contexts are popped, which calls143 the :meth:`~Flask.teardown_request` and144 :meth:`~Flask.teardown_appcontext` functions. These functions are145 called even if an unhandled exception was raised at any point above.146128An 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.147If an exception is raised before the teardown functions, Flask tries to148match it with an :meth:`~Flask.errorhandler` function to handle the149exception and return a response. If no error handler is found, or the150handler itself raises an exception, Flask returns a generic151``500 Internal Server Error`` response. The teardown functions are still152called, and are passed the exception object.153133The new teardown functions are supposed to be used as a replacement for134things that absolutely need to happen at the end of request.154If debug mode is enabled, unhandled exceptions are not converted to a155``500`` response and instead are propagated to the WSGI server. This156allows the development server to present the interactive debugger with157the traceback.158159160Teardown Callbacks137------------------161~~~~~~~~~~~~~~~~~~162139The teardown callbacks are special callbacks in that they are executed at140a different point. Strictly speaking they are independent of the actual141request handling as they are bound to the lifecycle of the142:class:`~flask.ctx.RequestContext` object. When the request context is143popped, the :meth:`~flask.Flask.teardown_request` functions are called.163The teardown callbacks are independent of the request dispatch, and are164instead called by the contexts when they are popped. The functions are165called even if there is an unhandled exception during dispatch, and for166manually pushed contexts. This means there is no guarantee that any167other parts of the request dispatch have run first. Be sure to write168these functions in a way that does not depend on other callbacks and169will not fail.170145This 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::171During testing, it can be useful to defer popping the contexts after the172request ends, so that their data can be accessed in the test function.173Using the :meth:`~Flask.test_client` as a ``with`` block to preserve the174contexts until the with block exits.175149 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 hand176.. code-block:: python177155 # 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 client178 from flask import Flask, request179159It's easy to see the behavior from the command line:180 app = Flask(__name__)181161>>> 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>>>182 @app.route('/')183 def hello():184 print('during view')185 return 'Hello, World!'186172Keep 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.187 @app.teardown_request188 def show_teardown(exception):189 print('after with block')190191 with app.test_request_context():192 print('during with block')193194 # teardown functions are called after the context with block exits195196 with app.test_client():197 client.get('/')198 # the contexts are not popped even though the request ended199 print(request.path)200201 # the contexts are popped and teardown functions are called after202 # the client with block exists203204205Signals206~~~~~~~207208If :data:`~signals.signals_available` is true, the following signals are209sent:210211#. :data:`request_started` is sent before the212 :meth:`~Flask.before_request` functions are called.213214#. :data:`request_finished` is sent after the215 :meth:`~Flask.after_request` functions are called.216217#. :data:`got_request_exception` is sent when an exception begins to218 be handled, but before an :meth:`~Flask.errorhandler` is looked up or219 called.220221#. :data:`request_tearing_down` is sent after the222 :meth:`~Flask.teardown_request` functions are called.223224225Context Preservation on Error226-----------------------------227228At the end of a request, the request context is popped and all data229associated with it is destroyed. If an error occurs during development,230it is useful to delay destroying the data for debugging purposes.231232When the development server is running in development mode (the233``FLASK_ENV`` environment variable is set to ``'development'``), the234error and data will be preserved and shown in the interactive debugger.235236This behavior can be controlled with the237:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it238defaults to ``True`` in the development environment.239240Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it241will cause your application to leak memory on exceptions.242243244.. _notes-on-proxies:245246Notes On Proxies247----------------248183Some 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.249Some of the objects provided by Flask are proxies to other objects. The250proxies are accessed in the same way for each worker thread, but251point to the unique object bound to each worker behind the scenes as252described on this page.253254Most of the time you don't have to care about that, but there are some255exceptions where it is good to know that this object is an actual proxy:256191- 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`)257- The proxy objects cannot fake their type as the actual object types.258 If you want to perform instance checks, you have to do that on the259 object being proxied.260- If the specific object reference is important, for example for261 sending :ref:`signals` or passing data to a background thread.262197If you need to get access to the underlying object that is proxied, you198can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::263If you need to access the underlying object that is proxied, use the264:meth:`~werkzeug.local.LocalProxy._get_current_object` method::265266 app = current_app._get_current_object()267 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. If debug mode is set to off, the context218is not preserved.219220Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221as it will cause your application to leak memory on exceptions. However,222it can be useful during development to get the same error preserving223behavior as debug mode when attempting to debug an error that224only occurs under production settings.
modified:flask/app.py+105 added-58 removed
2104 unmodified lines
2105 self.session_interface.save_session(self, ctx.session, response)2106 return response21072108 def do_teardown_request(self, exc=_sentinel):2109 """Called after the actual request dispatching and will2110 call every as :meth:`teardown_request` decorated function. This is2111 not actually called by the :class:`Flask` object itself but is always2112 triggered when the request context is popped. That way we have a2113 tighter control over certain resources under testing environments.2109 """Called after the request is dispatched and the response is2110 returned, right before the request context is popped.21112112 This calls all functions decorated with2113 :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`2114 if a blueprint handled the request. Finally, the2115 :data:`request_tearing_down` signal is sent.21162117 This is called by2118 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2119 which may be delayed during testing to maintain access to2120 resources.21212122 :param exc: An unhandled exception raised while dispatching the2123 request. Detected from the current exception information if2124 not passed. Passed to each teardown function.21252126 .. versionchanged:: 0.92116 Added the `exc` argument. Previously this was always using the2117 current exception information.2127 Added the ``exc`` argument.2128 """2129 if exc is _sentinel:2130 exc = sys.exc_info()[1]2131 funcs = reversed(self.teardown_request_funcs.get(None, ()))
4 unmodified lines
2136 func(exc)2137 request_tearing_down.send(self, exc=exc)21382139 def do_teardown_appcontext(self, exc=_sentinel):2130 """Called when an application context is popped. This works pretty2131 much the same as :meth:`do_teardown_request` but for the application2132 context.2140 """Called right before the application context is popped.21412142 When handling a request, the application context is popped2143 after the request context. See :meth:`do_teardown_request`.21442145 This calls all functions decorated with2146 :meth:`teardown_appcontext`. Then the2147 :data:`appcontext_tearing_down` signal is sent.21482149 This is called by2150 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.21512152 .. versionadded:: 0.92153 """2154 if exc is _sentinel:2155 exc = sys.exc_info()[1]
1 unmodified line
2157 func(exc)2158 appcontext_tearing_down.send(self, exc=exc)21592160 def app_context(self):2143 """Binds the application only. For as long as the application is bound2144 to the current context the :data:`flask.current_app` points to that2145 application. An application context is automatically created when a2146 request context is pushed if necessary.2161 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2162 block to push the context, which will make :data:`current_app`2163 point at this application.21642148 Example usage::2165 An application context is automatically pushed by2166 :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2167 when handling a request, and when running a CLI command. Use2168 this to manually create a context outside of these situations.21692170 ::21712172 with app.app_context():2151 ...2173 init_db()21742175 See :doc:`/appcontext`.21762177 .. versionadded:: 0.92178 """2179 return AppContext(self)21802181 def request_context(self, environ):2158 """Creates a :class:`~flask.ctx.RequestContext` from the given2159 environment and binds it to the current context. This must be used in2160 combination with the ``with`` statement because the request is only bound2161 to the current context for the duration of the ``with`` block.2182 """Create a :class:`~flask.ctx.RequestContext` representing a2183 WSGI environment. Use a ``with`` block to push the context,2184 which will make :data:`request` point at this request.21852163 Example usage::2186 See :doc:`/reqcontext`.21872165 with app.request_context(environ):2166 do_something_with(request)2188 Typically you should not call this from your own code. A request2189 context is automatically pushed by the :meth:`wsgi_app` when2190 handling a request. Use :meth:`test_request_context` to create2191 an environment and context instead of this method.21922168 The object returned can also be used without the ``with`` statement2169 which is useful for working in the shell. The example above is2170 doing exactly the same as this code::21712172 ctx = app.request_context(environ)2173 ctx.push()2174 try:2175 do_something_with(request)2176 finally:2177 ctx.pop()21782179 .. versionchanged:: 0.32180 Added support for non-with statement usage and ``with`` statement2181 is now passed the ctx object.21822193 :param environ: a WSGI environment2194 """2195 return RequestContext(self, environ)21962197 def test_request_context(self, *args, **kwargs):2188 """Creates a :class:`~flask.ctx.RequestContext` from the given values2189 (see :class:`werkzeug.test.EnvironBuilder` for more information, this2190 function accepts the same arguments plus two additional).2198 """Create a :class:`~flask.ctx.RequestContext` for a WSGI2199 environment created from the given values. This is mostly useful2200 during testing, where you may want to run a function that uses2201 request data without dispatching a full request.22022192 Additional arguments (only if ``base_url`` is not specified):2203 See :doc:`/reqcontext`.22042194 :param subdomain: subdomain to use for route matching2195 :param url_scheme: scheme for the request, default2196 ``PREFERRED_URL_SCHEME`` or ``http``.2197 """2205 Use a ``with`` block to push the context, which will make2206 :data:`request` point at the request for the created2207 environment. ::22082209 with test_request_context(...):2210 generate_report()22112212 When using the shell, it may be easier to push and pop the2213 context manually to avoid indentation. ::22142215 ctx = app.test_request_context(...)2216 ctx.push()2217 ...2218 ctx.pop()22192220 Takes the same arguments as Werkzeug's2221 :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2222 the application. See the linked Werkzeug docs for most of the2223 available arguments. Flask-specific behavior is listed here.22242225 :param path: URL path being requested.2226 :param base_url: Base URL where the app is being served, which2227 ``path`` is relative to. If not given, built from2228 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2229 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2230 :param subdomain: Subdomain name to append to2231 :data:`SERVER_NAME`.2232 :param url_scheme: Scheme to use instead of2233 :data:`PREFERRED_URL_SCHEME`.2234 :param data: The request body, either as a string or a dict of2235 form keys and values.2236 :param json: If given, this is serialized as JSON and passed as2237 ``data``. Also defaults ``content_type`` to2238 ``application/json``.2239 :param args: other positional arguments passed to2240 :class:`~werkzeug.test.EnvironBuilder`.2241 :param kwargs: other keyword arguments passed to2242 :class:`~werkzeug.test.EnvironBuilder`.2243 """2244 from flask.testing import make_test_environ_builder22452246 builder = make_test_environ_builder(self, *args, **kwargs)2247
2 unmodified lines
2250 finally:2251 builder.close()22522253 def wsgi_app(self, environ, start_response):2209 """The actual WSGI application. This is not implemented in2210 `__call__` so that middlewares can be applied without losing a2211 reference to the class. So instead of doing this::2254 """The actual WSGI application. This is not implemented in2255 :meth:`__call__` so that middlewares can be applied without2256 losing a reference to the app object. Instead of doing this::22572258 app = MyMiddleware(app)22592260 It's a better idea to do this instead::
3 unmodified lines
2264 Then you still have the original application object around and2265 can continue to call methods on it.22662267 .. versionchanged:: 0.72223 The behavior of the before and after request callbacks was changed2224 under error conditions and a new callback was added that will2225 always execute at the end of the request, independent on if an2226 error occurred or not. See :ref:`callbacks-and-errors`.2268 Teardown events for the request and app contexts are called2269 even if an unhandled error occurs. Other events may not be2270 called depending on when an error occurs during dispatch.2271 See :ref:`callbacks-and-errors`.22722228 :param environ: a WSGI environment2229 :param start_response: a callable accepting a status code,2230 a list of headers and an optional2231 exception context to start the response2273 :param environ: A WSGI environment.2274 :param start_response: A callable accepting a status code,2275 a list of headers, and an optional exception context to2276 start the response.2277 """2278 ctx = self.request_context(environ)2279 error = None2280 try:
12 unmodified lines
2293 error = None2294 ctx.auto_pop(error)22952296 def __call__(self, environ, start_response):2252 """Shortcut for :attr:`wsgi_app`."""2297 """The WSGI server calls the Flask application object as the2298 WSGI application. This calls :meth:`wsgi_app` which can be2299 wrapped to applying middleware."""2300 return self.wsgi_app(environ, start_response)23012302 def __repr__(self):2303 return '<%s %r>' % (
3 unmodified lines
modified:flask/ctx.py+43 added-1 removed
22 unmodified lines
23_sentinel = object()242526class _AppCtxGlobals(object):27 """A plain object."""27 """A plain object. Used as a namespace for storing data during an28 application context.2930 Creating an app context automatically creates this object, which is31 made available as the :data:`g` proxy.3233 .. describe:: 'key' in g3435 Check whether an attribute is present.3637 .. versionadded:: 0.103839 .. describe:: iter(g)4041 Return an iterator over the attribute names.4243 .. versionadded:: 0.1044 """4546 def get(self, name, default=None):47 """Get an attribute by name, or a default value. Like48 :meth:`dict.get`.4950 :param name: Name of attribute to get.51 :param default: Value to return if the attribute is not present.5253 .. versionadded:: 0.1054 """55 return self.__dict__.get(name, default)5657 def pop(self, name, default=_sentinel):58 """Get and remove an attribute by name. Like :meth:`dict.pop`.5960 :param name: Name of attribute to pop.61 :param default: Value to return if the attribute is not present,62 instead of raise a ``KeyError``.6364 .. versionadded:: 0.1165 """66 if default is _sentinel:67 return self.__dict__.pop(name)68 else:69 return self.__dict__.pop(name, default)7071 def setdefault(self, name, default=None):72 """Get the value of an attribute if it is present, otherwise73 set and return a default value. Like :meth:`dict.setdefault`.7475 :param name: Name of attribute to get.76 :param: default: Value to set and return if the attribute is not77 present.7879 .. versionadded:: 0.1180 """81 return self.__dict__.setdefault(name, default)8283 def __contains__(self, item):84 return item in self.__dict__
373 unmodified lines
modified:flask/globals.py+2 added-2 removed
23 unmodified lines
24_app_ctx_err_msg = '''\25Working outside of application context.2627This typically means that you attempted to use functionality that needed28to interface with the current application object in a way. To solve29this set up an application context with app.app_context(). See the28to interface with the current application object in some way. To solve29this, set up an application context with app.app_context(). See the30documentation for more information.\31'''3233
28 unmodified lines
modified:flask/testing.py+20 added-1 removed
23 unmodified lines
24def make_test_environ_builder(25 app, path='/', base_url=None, subdomain=None, url_scheme=None,26 *args, **kwargs27):28 """Creates a new test builder with some application defaults thrown in."""28 """Create a :class:`~werkzeug.test.EnvironBuilder`, taking some29 defaults from the application.3031 :param app: The Flask application to configure the environment from.32 :param path: URL path being requested.33 :param base_url: Base URL where the app is being served, which34 ``path`` is relative to. If not given, built from35 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,36 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.37 :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.38 :param url_scheme: Scheme to use instead of39 :data:`PREFERRED_URL_SCHEME`.40 :param json: If given, this is serialized as JSON and passed as41 ``data``. Also defaults ``content_type`` to42 ``application/json``.43 :param args: other positional arguments passed to44 :class:`~werkzeug.test.EnvironBuilder`.45 :param kwargs: other keyword arguments passed to46 :class:`~werkzeug.test.EnvironBuilder`.47 """4849 assert (50 not (base_url or subdomain or url_scheme)51 or (base_url is not None) != bool(subdomain or url_scheme)52 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'
198 unmodified lines