rework context docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 47a0086 · 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
Provenance
- Commit
2411707- Tree
3984ada- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
47a0086
7 files changed+531 added−364 removed
modified:docs/api.rst+47 added-46 removed
209 unmodified lines210 thing, like it does for :class:`request` and :class:`session`.211 212 .. data:: g213 214- 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`.218 217- 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.222 223- 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.224 227- 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.227 230- 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:230 233- As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same234- way you would use them on a dictionary.231 236- This is a proxy. See :ref:`notes-on-proxies` for more information.237-238-232 Useful Functions and Classes233 ----------------------------234 235 .. data:: current_app236 244- 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.241 250- 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`.246 247+ This is a proxy. See :ref:`notes-on-proxies` for more information.248+249 .. autofunction:: has_request_context250 251 .. autofunction:: copy_current_request_context252 127 unmodified lines380 :members:381 382 .. data:: _request_ctx_stack383 387- 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.389 392- 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:392 395- `app`393+ `app`394 the active Flask application.395 398- `url_adapter`396+ `url_adapter`397 the URL adapter that was used to match the request.398 401- `request`399+ `request`400 the current request object.401 404- `session`402+ `session`403 the active session object.404 407- `g`405+ `g`406 an object with all the attributes of the :data:`flask.g` object.407 410- `flashes`408+ `flashes`409 an internal cache for the flashed messages.410 413- Example usage::411+ Example usage::412 415- from flask import _request_ctx_stack413+ from flask import _request_ctx_stack414 417- 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.session419 420 .. autoclass:: flask.ctx.AppContext421 :members:422 423 .. data:: _app_ctx_stack424 427- 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.430 430- .. versionadded:: 0.9431+ .. versionadded:: 0.9432 433 .. autoclass:: flask.blueprints.BlueprintSetupState434 :members:435 387 unmodified linesmodified:docs/appcontext.rst+113 added-98 removed
1+.. currentmodule:: flask2+3 .. _app-context:4 5 The Application Context6 =======================7 6-.. versionadded:: 0.98+The application context keeps track of the application-level data during9+a request, CLI command, or other activity. Rather than passing the10+application around to each function, the :data:`current_app` and11+:data:`g` proxies are accessed instead.12 8-One of the design ideas behind Flask is that there are at least two9-different “states” in which code is executed:13+This is similar to the :doc:`/reqcontext`, which keeps track of14+request-level data during a request. A corresponding application context15+is pushed when a request context is pushed.16 11-1. The application setup state, in which the application implicitly is12-on the module level.17+Purpose of the Context18+----------------------19 14- 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:20+The :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`` instance23+within the modules in your project is prone to circular import issues.24+When using the :doc:`app factory pattern </patterns/appfactories>` or25+writing reusable :doc:`blueprints </blueprints>` or26+:doc:`extensions </extensions>` there won't be an ``app`` instance to27+import at all.28 18- - 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.29+Flask solves this issue with the *application context*. Rather than30+referring to an ``app`` directly, you use the the :data:`current_app`31+proxy, which points to the application handling the current activity.32 24-2. In contrast, in the request handling state, a couple of other rules25-exist:33+Flask automatically *pushes* an application context when handling a34+request. View functions, error handlers, and other functions that run35+during a request will have access to :data:`current_app`.36 27- - 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.37+Flask will also automatically push an app context when running CLI38+commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.39 31-3. There is also a third state somewhere in between 'module-level' and32-'request-handling':40 34- 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.41+Lifetime of the Context42+-----------------------43 40-The application context is what powers the :data:`~flask.current_app`41-context local.44+The application context is created and destroyed as necessary. When a45+Flask application begins handling a request, it pushes an application46+context and a :doc:`request context </reqcontext>`. When the request47+ends it pops the request context then the application context.48+Typically, an application context will have the same lifetime as a49+request.50 43-Purpose of the Application Context44-----------------------------------51+See :doc:`/reqcontext` for more information about how the contexts work52+and the full lifecycle of a request.53 46-The main reason for the application's context existence is that in the47-past a bunch of functionality was attached to the request context for lack48-of a better solution. Since one of the pillars of Flask's design is that49-you can have more than one application in the same Python process.54 51-So how does the code find the “right” application? In the past we52-recommended passing applications around explicitly, but that caused issues53-with libraries that were not designed with that in mind.55+Manually Push a Context56+-----------------------57 55-A common workaround for that problem was to use the56-:data:`~flask.current_app` proxy later on, which was bound to the current57-request's application reference. Since creating such a request context is58-an unnecessarily expensive operation in case there is no request around,59-the application context was introduced.58+If you try to access :data:`current_app`, or anything that uses it,59+outside an application context, you'll get this error message:60 61-Creating an Application Context62--------------------------------61+.. code-block:: pytb62 64-There are two ways to make an application context. The first one is65-implicit: whenever a request context is pushed, an application context66-will be created alongside if this is necessary. As a result, you can67-ignore the existence of the application context unless you need it.63+ RuntimeError: Working outside of application context.64 69-The 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().68 72- from flask import Flask, current_app69+If you see that error while configuring your application, such as when70+initializing an extension, you can push a context manually since you71+have direct access to the ``app``. Use :meth:`~Flask.app_context` in a72+``with`` block, and everything that runs in the block will have access73+to :data:`current_app`. ::74 74- 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__)77 79-The application context is also used by the :func:`~flask.url_for`80-function in case a ``SERVER_NAME`` was configured. This allows you to81-generate URLs even in the absence of a request.78+ with app.app_context():79+ init_db()80 83-If no request context has been pushed and an application context has84-not been explicitly set, a ``RuntimeError`` will be raised. ::81+ return app82 86- RuntimeError: Working outside of application context.83+If you see that error somewhere else in your code not related to84+configuring the application, it most likely indicates that you should85+move that code into a view function or CLI command.86 88-Locality of the Context89------------------------87 91-The application context is created and destroyed as necessary. It never92-moves between threads and it will not be shared between requests. As such93-it is the perfect place to store database connection information and other94-things. The internal stack object is called :data:`flask._app_ctx_stack`.95-Extensions are free to store additional information on the topmost level,96-assuming they pick a sufficiently unique name and should put their97-information there, instead of on the :data:`flask.g` object which is reserved98-for user code.88+Storing Data89+------------90 100-For more information about that, see :ref:`extension-dev`.91+The application context is a good place to store common data during a92+request or CLI command. Flask provides the :data:`g object <g>` for this93+purpose. It is a simple namespace object that has the same lifetime as94+an application context.95 102-Context 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.102 105-The context is typically used to cache resources that need to be created106-on a per-request or usage case. For instance, database connections are107-destined to go there. When storing things on the application context108-unique names should be chosen as this is a place that is shared between109-Flask applications and extensions.103+A common use for :data:`g` is to manage resources during a request.104 111-The most common usage is to split resource management into two parts:105+1. ``get_X()`` creates resource ``X`` if it does not exist, caching it106+ as ``g.X``.107+2. ``teardown_X()`` closes or otherwise deallocates the resource if it108+ exists. It is registered as a :meth:`~Flask.teardown_appcontext`109+ handler.110 113-1. an implicit resource caching on the context.114-2. a context teardown based resource deallocation.111+For example, you can manage a database connection using this pattern::112 116-Generally there would be a ``get_X()`` function that creates resource117-``X`` if it does not exist yet and otherwise returns the same resource,118-and a ``teardown_X()`` function that is registered as teardown handler.119-120-This is an example that connects to a database::121-122- import sqlite3113 from flask import g114 115 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()118 119+ return g.db120+121 @app.teardown_appcontext132- def teardown_db(exception):133- db = getattr(g, '_database', None)122+ def teardown_db():123+ db = g.pop('db', None)124+125 if db is not None:126 db.close()127 137-The first time ``get_db()`` is called the connection will be established.138-To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::128+During a request, every call to ``get_db()`` will return the same129+connection, and it will be closed automatically at the end of the130+request.131 132+You can use :class:`~werkzeug.local.LocalProxy` to make a new context133+local from ``get_db()``::134+135 from werkzeug.local import LocalProxy136 db = LocalProxy(get_db)137 143-That way a user can directly access ``db`` which internally calls144-``get_db()``.138+Accessing ``db`` will call ``get_db`` internally, in the same way that139+:data:`current_app` works.140+141+----142+143+If you're writing an extension, :data:`g` should be reserved for user144+code. You may store internal data on the context itself, but be sure to145+use a sufficiently unique name. The current context is accessed with146+:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see147+:doc:`extensiondev`.148+149+150+Events and Signals151+------------------152+153+The application will call functions registered with154+:meth:`~Flask.teardown_appcontext` when the application context is155+popped.156+157+If :data:`~signals.signals_available` is true, the following signals are158+sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and159+:data:`appcontext_popped`.modified:docs/reqcontext.rst+201 added-158 removed
1+.. currentmodule:: flask2+3 .. _request-context:4 5 The Request Context6 ===================7 6-This document describes the behavior in Flask 0.7 which is mostly in line7-with the old behavior but has some small, subtle differences.8+The request context keeps track of the request-level data during a9+request. Rather than passing the request object to each function that10+runs during a request, the :data:`request` and :data:`session` proxies11+are accessed instead.12 9-It is recommended that you read the :ref:`app-context` chapter first.13+This is similar to the :doc:`/appcontext`, which keeps track of the14+application-level data independent of a request. A corresponding15+application context is pushed when a request context is pushed.16 11-Diving into Context Locals12---------------------------17 14-Say you have a utility function that returns the URL the user should be15-redirected to. Imagine it would always redirect to the URL's ``next``16-parameter or the HTTP referrer or the index page::18+Purpose of the Context19+----------------------20 18- from flask import request, url_for21+When the :class:`Flask` application handles a request, it creates a22+:class:`Request` object based on the environment it received from the23+WSGI server. Because a *worker* (thread, process, or coroutine depending24+on the server) handles only one request at a time, the request data can25+be considered global to that worker during that request. Flask uses the26+term *context local* for this.27 20- def redirect_url():21- return request.args.get('next') or \22- request.referrer or \23- url_for('index')28+Flask automatically *pushes* a request context when handling a request.29+View functions, error handlers, and other functions that run during a30+request will have access to the :data:`request` proxy, which points to31+the request object for the current request.32 25-As you can see, it accesses the request object. If you try to run this26-from a plain Python shell, this is the exception you will see:33 28->>> redirect_url()29-Traceback (most recent call last):30- File "<stdin>", line 1, in <module>31-AttributeError: 'NoneType' object has no attribute 'request'34+Lifetime of the Context35+-----------------------36 33-That makes a lot of sense because we currently do not have a request we34-could access. So we have to make a request and bind it to the current35-context. The :attr:`~flask.Flask.test_request_context` method can create36-us a :class:`~flask.ctx.RequestContext`:37+When a Flask application begins handling a request, it pushes a request38+context, which also pushes an :doc:`/appcontext`. When the request ends39+it pops the request context then the application context.40 38->>> ctx = app.test_request_context('/?next=http://example.com/')41+The context is unique to each thread (or other worker type).42+:data:`request` cannot be passed to another thread, the other thread43+will have a different context stack and will not know about the request44+the parent thread was pointing to.45 40-This context can be used in two ways. Either with the ``with`` statement41-or by calling the :meth:`~flask.ctx.RequestContext.push` and42-:meth:`~flask.ctx.RequestContext.pop` methods:46+Context locals are implemented in Werkzeug. See :doc:`werkzeug:local`47+for more information on how this works internally.48 44->>> ctx.push()49 46-From that point onwards you can work with the request object:50+Manually Push a Context51+-----------------------52 48->>> redirect_url()49-u'http://example.com/'53+If you try to access :data:`request`, or anything that uses it, outside54+a request context, you'll get this error message:55 51-Until you call `pop`:56+.. code-block:: pytb57 53->>> ctx.pop()58+ RuntimeError: Working outside of request context.59 55-Because the request context is internally maintained as a stack you can56-push and pop multiple times. This is very handy to implement things like57-internal 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.63 59-For more information of how to utilize the request context from the60-interactive Python shell, head over to the :ref:`shell` chapter.64+This should typically only happen when testing code that expects an65+active request. One option is to use the66+:meth:`test client <Flask.test_client>` to simulate a full request. Or67+you can use :meth:`~Flask.test_request_context` in a ``with`` block, and68+everything that runs in the block will have access to :data:`request`,69+populated with your test data. ::70 71+ def generate_report(year):72+ format = request.args.get('format')73+ ...74+75+ with app.test_request_context(76+ '/make_report/2017', data={'format': 'short'}):77+ generate_report()78+79+If you see that error somewhere else in your code not related to80+testing, it most likely indicates that you should move that code into a81+view function.82+83+For information on how to use the request context from the interactive84+Python shell, see :doc:`/shell`.85+86+87 How the Context Works88 ---------------------89 65-If you look into how the Flask WSGI application internally works, you will66-find a piece of code that looks very much like this::90+The :meth:`Flask.wsgi_app` method is called to handle each request. It91+manages the contexts during the request. Internally, the request and92+application contexts work as stacks, :data:`_request_ctx_stack` and93+:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the94+proxies that depend on them are available and point at information from95+the top context on the stack.96 68- 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)97+When the request starts, a :class:`~ctx.RequestContext` is created and98+pushed, which creates and pushes an :class:`~ctx.AppContext` first if99+a context for that application is not already the top context. While100+these contexts are pushed, the :data:`current_app`, :data:`g`,101+:data:`request`, and :data:`session` proxies are available to the102+original thread handling the request.103 76-The method :meth:`~Flask.request_context` returns a new77-:class:`~flask.ctx.RequestContext` object and uses it in combination with78-the ``with`` statement to bind the context. Everything that is called from79-the same thread from this point onwards until the end of the ``with``80-statement will have access to the request globals (:data:`flask.request`81-and others).104+Because the contexts are stacks, other contexts may be pushed to change105+the proxies during a request. While this is not a common pattern, it106+can be used in advanced applications to, for example, do internal107+redirects or chain different applications together.108 83-The request context internally works like a stack: The topmost level on84-the stack is the current active request.85-:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on86-the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the87-stack again. On popping the application's88-:func:`~flask.Flask.teardown_request` functions are also executed.109+After the request is dispatched and a response is generated and sent,110+the request context is popped, which then pops the application context.111+Immediately before they are popped, the :meth:`~Flask.teardown_request`112+and :meth:`~Flask.teardown_appcontext` functions are are executed. These113+execute even if an unhandled exception occurred during dispatch.114 90-Another thing of note is that the request context will automatically also91-create an :ref:`application context <app-context>` when it's pushed and92-there is no application context for that application so far.115 116 .. _callbacks-and-errors:117 118 Callbacks and Errors119 --------------------120 99-What happens if an error occurs in Flask during request processing? This100-particular behavior changed in 0.7 because we wanted to make it easier to101-understand what is actually happening. The new behavior is quite simple:121+Flask dispatches a request in multiple stages which can affect the122+request, response, and how errors are handled. The contexts are active123+during all of these stages.124 103-1. 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.125+A :class:`Blueprint` can add handlers for these events that are specific126+to the blueprint. The handlers for a blueprint will run if the blueprint127+owns the route that matches the request.128 108-2. 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.133 112-3. 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.137 116-4. 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.141 122-Now what happens on errors? If you are not in debug mode and an exception is not 123-caught, the 500 internal server handler is called. In debug mode 124-however the exception is not further processed and bubbles up to the WSGI 125-server. That way things like the interactive debugger can provide helpful126-debug 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.146 128-An important change in 0.7 is that the internal server error is now no129-longer post processed by the after request callbacks and after request130-callbacks are no longer guaranteed to be executed. This way the internal131-dispatching code looks cleaner and is easier to customize and understand.147+If an exception is raised before the teardown functions, Flask tries to148+match it with an :meth:`~Flask.errorhandler` function to handle the149+exception and return a response. If no error handler is found, or the150+handler itself raises an exception, Flask returns a generic151+``500 Internal Server Error`` response. The teardown functions are still152+called, and are passed the exception object.153 133-The new teardown functions are supposed to be used as a replacement for134-things that absolutely need to happen at the end of request.154+If debug mode is enabled, unhandled exceptions are not converted to a155+``500`` response and instead are propagated to the WSGI server. This156+allows the development server to present the interactive debugger with157+the traceback.158 159+160 Teardown Callbacks137-------------------161+~~~~~~~~~~~~~~~~~~162 139-The teardown callbacks are special callbacks in that they are executed at140-a different point. Strictly speaking they are independent of the actual141-request handling as they are bound to the lifecycle of the142-:class:`~flask.ctx.RequestContext` object. When the request context is143-popped, the :meth:`~flask.Flask.teardown_request` functions are called.163+The teardown callbacks are independent of the request dispatch, and are164+instead called by the contexts when they are popped. The functions are165+called even if there is an unhandled exception during dispatch, and for166+manually pushed contexts. This means there is no guarantee that any167+other parts of the request dispatch have run first. Be sure to write168+these functions in a way that does not depend on other callbacks and169+will not fail.170 145-This is important to know if the life of the request context is prolonged146-by using the test client in a with statement or when using the request147-context from the command line::171+During testing, it can be useful to defer popping the contexts after the172+request ends, so that their data can be accessed in the test function.173+Using the :meth:`~Flask.test_client` as a ``with`` block to preserve the174+contexts until the with block exits.175 149- 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:: python177 155- # 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, request179 159-It's easy to see the behavior from the command line:180+ app = Flask(__name__)181 161->>> 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()169-this runs after request170->>>182+ @app.route('/')183+ def hello():184+ print('during view')185+ return 'Hello, World!'186 172-Keep in mind that teardown callbacks are always executed, even if173-before-request callbacks were not executed yet but an exception happened.174-Certain parts of the test system might also temporarily create a request175-context without calling the before-request handlers. Make sure to write176-your teardown-request handlers in a way that they will never fail.187+ @app.teardown_request188+ def show_teardown(exception):189+ print('after with block')190 191+ with app.test_request_context():192+ print('during with block')193+194+ # teardown functions are called after the context with block exits195+196+ with app.test_client():197+ client.get('/')198+ # the contexts are not popped even though the request ended199+ print(request.path)200+201+ # the contexts are popped and teardown functions are called after202+ # the client with block exists203+204+205+Signals206+~~~~~~~207+208+If :data:`~signals.signals_available` is true, the following signals are209+sent:210+211+#. :data:`request_started` is sent before the212+ :meth:`~Flask.before_request` functions are called.213+214+#. :data:`request_finished` is sent after the215+ :meth:`~Flask.after_request` functions are called.216+217+#. :data:`got_request_exception` is sent when an exception begins to218+ be handled, but before an :meth:`~Flask.errorhandler` is looked up or219+ called.220+221+#. :data:`request_tearing_down` is sent after the222+ :meth:`~Flask.teardown_request` functions are called.223+224+225+Context Preservation on Error226+-----------------------------227+228+At the end of a request, the request context is popped and all data229+associated with it is destroyed. If an error occurs during development,230+it is useful to delay destroying the data for debugging purposes.231+232+When the development server is running in development mode (the233+``FLASK_ENV`` environment variable is set to ``'development'``), the234+error and data will be preserved and shown in the interactive debugger.235+236+This behavior can be controlled with the237+:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it238+defaults to ``True`` in the development environment.239+240+Do not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it241+will cause your application to leak memory on exceptions.242+243+244 .. _notes-on-proxies:245 246 Notes On Proxies247 ----------------248 183-Some of the objects provided by Flask are proxies to other objects. The184-reason behind this is that these proxies are shared between threads and185-they have to dispatch to the actual object bound to a thread behind the186-scenes as necessary.249+Some of the objects provided by Flask are proxies to other objects. The250+proxies are accessed in the same way for each worker thread, but251+point to the unique object bound to each worker behind the scenes as252+described on this page.253 254 Most of the time you don't have to care about that, but there are some255 exceptions where it is good to know that this object is an actual proxy:256 191-- 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.262 197-If you need to get access to the underlying object that is proxied, you198-can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::263+If you need to access the underlying object that is proxied, use the264+:meth:`~werkzeug.local.LocalProxy._get_current_object` method::265 266 app = current_app._get_current_object()267 my_signal.send(app)202-203-Context Preservation on Error204------------------------------205-206-If an error occurs or not, at the end of the request the request context207-is popped and all data associated with it is destroyed. During208-development however that can be problematic as you might want to have the209-information around for a longer time in case an exception occurred. In210-Flask 0.6 and earlier in debug mode, if an exception occurred, the211-request context was not popped so that the interactive debugger can still212-provide you with important information.213-214-Starting with Flask 0.7 you have finer control over that behavior by215-setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216-default it's linked to the setting of ``DEBUG``. If the application is in217-debug mode the context is preserved. If debug mode is set to off, the context218-is not preserved.219-220-Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221-as it will cause your application to leak memory on exceptions. However,222-it can be useful during development to get the same error preserving223-behavior as debug mode when attempting to debug an error that224-only occurs under production settings.modified:flask/app.py+105 added-58 removed
2104 unmodified lines2105 self.session_interface.save_session(self, ctx.session, response)2106 return response2107 2108 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.2111 2112+ 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.2116+2117+ This is called by2118+ :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2119+ which may be delayed during testing to maintain access to2120+ resources.2121+2122+ :param exc: An unhandled exception raised while dispatching the2123+ request. Detected from the current exception information if2124+ not passed. Passed to each teardown function.2125+2126 .. 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 lines2136 func(exc)2137 request_tearing_down.send(self, exc=exc)2138 2139 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.2141 2142+ When handling a request, the application context is popped2143+ after the request context. See :meth:`do_teardown_request`.2144+2145+ This calls all functions decorated with2146+ :meth:`teardown_appcontext`. Then the2147+ :data:`appcontext_tearing_down` signal is sent.2148+2149+ This is called by2150+ :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.2151+2152 .. versionadded:: 0.92153 """2154 if exc is _sentinel:2155 exc = sys.exc_info()[1]1 unmodified line2157 func(exc)2158 appcontext_tearing_down.send(self, exc=exc)2159 2160 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.2164 2148- 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.2169 2170+ ::2171+2172 with app.app_context():2151- ...2173+ init_db()2174 2175+ See :doc:`/appcontext`.2176+2177 .. versionadded:: 0.92178 """2179 return AppContext(self)2180 2181 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.2185 2163- Example usage::2186+ See :doc:`/reqcontext`.2187 2165- 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.2192 2168- 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::2171-2172- ctx = app.request_context(environ)2173- ctx.push()2174- try:2175- do_something_with(request)2176- finally:2177- ctx.pop()2178-2179- .. versionchanged:: 0.32180- Added support for non-with statement usage and ``with`` statement2181- is now passed the ctx object.2182-2193 :param environ: a WSGI environment2194 """2195 return RequestContext(self, environ)2196 2197 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.2202 2192- Additional arguments (only if ``base_url`` is not specified):2203+ See :doc:`/reqcontext`.2204 2194- :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. ::2208 2209+ with test_request_context(...):2210+ generate_report()2211+2212+ When using the shell, it may be easier to push and pop the2213+ context manually to avoid indentation. ::2214+2215+ ctx = app.test_request_context(...)2216+ ctx.push()2217+ ...2218+ ctx.pop()2219+2220+ 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.2224+2225+ :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_builder2245 2246 builder = make_test_environ_builder(self, *args, **kwargs)2247 2 unmodified lines2250 finally:2251 builder.close()2252 2253 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::2257 2258 app = MyMiddleware(app)2259 2260 It's a better idea to do this instead::3 unmodified lines2264 Then you still have the original application object around and2265 can continue to call methods on it.2266 2267 .. 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`.2272 2228- :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 lines2293 error = None2294 ctx.auto_pop(error)2295 2296 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)2301 2302 def __repr__(self):2303 return '<%s %r>' % (3 unmodified linesmodified:flask/ctx.py+43 added-1 removed
22 unmodified lines23 _sentinel = object()24 25 26 class _AppCtxGlobals(object):27- """A plain object."""27+ """A plain object. Used as a namespace for storing data during an28+ application context.29 30+ Creating an app context automatically creates this object, which is31+ made available as the :data:`g` proxy.32+33+ .. describe:: 'key' in g34+35+ Check whether an attribute is present.36+37+ .. versionadded:: 0.1038+39+ .. describe:: iter(g)40+41+ Return an iterator over the attribute names.42+43+ .. versionadded:: 0.1044+ """45+46 def get(self, name, default=None):47+ """Get an attribute by name, or a default value. Like48+ :meth:`dict.get`.49+50+ :param name: Name of attribute to get.51+ :param default: Value to return if the attribute is not present.52+53+ .. versionadded:: 0.1054+ """55 return self.__dict__.get(name, default)56 57 def pop(self, name, default=_sentinel):58+ """Get and remove an attribute by name. Like :meth:`dict.pop`.59+60+ :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``.63+64+ .. versionadded:: 0.1165+ """66 if default is _sentinel:67 return self.__dict__.pop(name)68 else:69 return self.__dict__.pop(name, default)70 71 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`.74+75+ :param name: Name of attribute to get.76+ :param: default: Value to set and return if the attribute is not77+ present.78+79+ .. versionadded:: 0.1180+ """81 return self.__dict__.setdefault(name, default)82 83 def __contains__(self, item):84 return item in self.__dict__373 unmodified linesmodified:flask/globals.py+2 added-2 removed
23 unmodified lines24 _app_ctx_err_msg = '''\25 Working outside of application context.26 27 This typically means that you attempted to use functionality that needed28-to interface with the current application object in a way. To solve29-this set up an application context with app.app_context(). See the28+to interface with the current application object in some way. To solve29+this, set up an application context with app.app_context(). See the30 documentation for more information.\31 '''32 33 28 unmodified linesmodified:flask/testing.py+20 added-1 removed
23 unmodified lines24 def 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.30 31+ :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+ """48+49 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