merge app and request context (#5812)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 3301232, c2705ff · Browse files · 36 files·+771 added−999 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
36 files+771 added−999 removed
- tests:+22 added−20 removed
- other:+749 added−979 removed
Provenance
- Commit
adf3636- Tree
68d947d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3301232- Parent 2
c2705ff
36 files changed+771 added−999 removed
modified:docs/patterns/sqlalchemy.rst+2 added-3 removed
129 unmodified lines130 bind=engine))131 def init_db():132 metadata.create_all(bind=engine)133 134-As in the declarative approach, you need to close the session after135-each request or application context shutdown. Put this into your136-application module::134+As in the declarative approach, you need to close the session after each app135+context. Put this into your application module::136 137 from yourapplication.database import db_session138 139 @app.teardown_appcontext74 unmodified linesmodified:docs/patterns/sqlite3.rst+3 added-3 removed
1 Using SQLite 3 with Flask2 =========================3 4-In Flask you can easily implement the opening of database connections on5-demand and closing them when the context dies (usually at the end of the6-request).4+You can implement a few functions to work with a SQLite connection during a5+request context. The connection is created the first time it's accessed,6+reused on subsequent access, until it is closed when the request context ends.7 8 Here is a simple example of how you can use SQLite 3 with Flask::9 10 import sqlite3137 unmodified linesmodified:docs/patterns/streaming.rst+5 added-5 removed
47 unmodified lines48 49 Streaming with Context50 ----------------------51 52-The :data:`~flask.request` will not be active while the generator is53-running, because the view has already returned at that point. If you try54-to access ``request``, you'll get a ``RuntimeError``.52+The :data:`.request` proxy will not be active while the generator is53+running, because the app has already returned control to the WSGI server at that54+point. If you try to access ``request``, you'll get a ``RuntimeError``.55 56 If your generator function relies on data in ``request``, use the57-:func:`~flask.stream_with_context` wrapper. This will keep the request58-context active during the generator.57+:func:`.stream_with_context` wrapper. This will keep the request context active58+during the generator.59 60 .. code-block:: python61 62 from flask import stream_with_context, request23 unmodified linesmodified:docs/tutorial/blog.rst+1 added-1 removed
303 unmodified lines304 The pattern ``{{ request.form['title'] or post['title'] }}`` is used to305 choose what data appears in the form. When the form hasn't been306 submitted, the original ``post`` data appears, but if invalid form data307 was posted you want to display that so the user can fix the error, so308-``request.form`` is used instead. :data:`request` is another variable308+``request.form`` is used instead. :data:`.request` is another variable309 that's automatically available in templates.310 311 312 Delete24 unmodified linesmodified:docs/tutorial/database.rst+3 added-3 removed
58 unmodified lines59 60 if db is not None:61 db.close()62 63-:data:`g` is a special object that is unique for each request. It is63+:data:`.g` is a special object that is unique for each request. It is64 used to store data that might be accessed by multiple functions during65 the request. The connection is stored and reused instead of creating a66 new connection if ``get_db`` is called a second time in the same67 request.68 69-:data:`current_app` is another special object that points to the Flask69+:data:`.current_app` is another special object that points to the Flask70 application handling the request. Since you used an application factory,71 there is no application object when writing the rest of your code.72 ``get_db`` will be called when the application has been created and is73-handling a request, so :data:`current_app` can be used.73+handling a request, so :data:`.current_app` can be used.74 75 :func:`sqlite3.connect` establishes a connection to the file pointed at76 by the ``DATABASE`` configuration key. This file doesn't have to exist77 yet, and won't until you initialize the database later.142 unmodified linesmodified:docs/tutorial/templates.rst+1 added-1 removed
69 unmodified lines70 {% endfor %}71 {% block content %}{% endblock %}72 </section>73 74-:data:`g` is automatically available in templates. Based on if74+:data:`.g` is automatically available in templates. Based on if75 ``g.user`` is set (from ``load_logged_in_user``), either the username76 and a log out link are displayed, or links to register and log in77 are displayed. :func:`url_for` is also automatically available, and is78 used to generate URLs to views instead of writing them out manually.109 unmodified linesmodified:docs/tutorial/tests.rst+3 added-3 removed
309 unmodified lines310 input and error messages without writing the same code three times.311 312 The tests for the ``login`` view are very similar to those for313 ``register``. Rather than testing the data in the database,314-:data:`session` should have ``user_id`` set after logging in.314+:data:`.session` should have ``user_id`` set after logging in.315 316 .. code-block:: python317 :caption: ``tests/test_auth.py``318 16 unmodified lines335 response = auth.login(username, password)336 assert message in response.data337 338 Using ``client`` in a ``with`` block allows accessing context variables339-such as :data:`session` after the response is returned. Normally,339+such as :data:`.session` after the response is returned. Normally,340 accessing ``session`` outside of a request would raise an error.341 342-Testing ``logout`` is the opposite of ``login``. :data:`session` should342+Testing ``logout`` is the opposite of ``login``. :data:`.session` should343 not contain ``user_id`` after logging out.344 345 .. code-block:: python346 :caption: ``tests/test_auth.py``213 unmodified linesmodified:docs/tutorial/views.rst+4 added-4 removed
206 unmodified lines207 #. :func:`~werkzeug.security.check_password_hash` hashes the submitted208 password in the same way as the stored hash and securely compares209 them. If they match, the password is valid.210 211-#. :data:`session` is a :class:`dict` that stores data across requests.211+#. :data:`.session` is a :class:`dict` that stores data across requests.212 When validation succeeds, the user's ``id`` is stored in a new213 session. The data is stored in a *cookie* that is sent to the214 browser, and the browser then sends it back with subsequent requests.215 Flask securely *signs* the data so that it can't be tampered with.216 217-Now that the user's ``id`` is stored in the :data:`session`, it will be217+Now that the user's ``id`` is stored in the :data:`.session`, it will be218 available on subsequent requests. At the beginning of each request, if219 a user is logged in their information should be loaded and made220 available to other views.221 13 unmodified lines235 236 :meth:`bp.before_app_request() <Blueprint.before_app_request>` registers237 a function that runs before the view function, no matter what URL is238 requested. ``load_logged_in_user`` checks if a user id is stored in the239-:data:`session` and gets that user's data from the database, storing it239+:data:`.session` and gets that user's data from the database, storing it240 on :data:`g.user <g>`, which lasts for the length of the request. If241 there is no user id, or if the id doesn't exist, ``g.user`` will be242 ``None``.243 244 245 Logout246 ------247 248-To log out, you need to remove the user id from the :data:`session`.248+To log out, you need to remove the user id from the :data:`.session`.249 Then ``load_logged_in_user`` won't load a user on subsequent requests.250 251 .. code-block:: python252 :caption: ``flaskr/auth.py``53 unmodified linesmodified:docs/api.rst+58 added-67 removed
29 unmodified lines30 :members:31 :inherited-members:32 :exclude-members: json_module33 34-.. attribute:: request34+.. data:: request35 36- To access incoming request data, you can use the global `request`37- object. Flask parses incoming request data for you and gives you38- access to it through that global object. Internally Flask makes39- sure that you always get the correct data for the active thread if you40- are in a multithreaded environment.36+ A proxy to the request data for the current request, an instance of37+ :class:`.Request`.38 42- This is a proxy. See :ref:`notes-on-proxies` for more information.39+ This is only available when a :doc:`request context </appcontext>` is40+ active.41 44- The request object is an instance of a :class:`~flask.Request`.42+ This is a proxy. See :ref:`context-visibility` for more information.43 44 45 Response Objects46 ----------------12 unmodified lines59 does this is by using a signed cookie. The user can look at the session60 contents, but can't modify it unless they know the secret key, so make sure to61 set that to something complex and unguessable.62 65-To access the current session you can use the :class:`session` object:63+To access the current session you can use the :data:`.session` proxy.64 67-.. class:: session65+.. data:: session66 69- The session object works pretty much like an ordinary dict, with the70- difference that it keeps track of modifications.67+ A proxy to the session data for the current request, an instance of68+ :class:`.SessionMixin`.69 72- This is a proxy. See :ref:`notes-on-proxies` for more information.70+ This is only available when a :doc:`request context </appcontext>` is71+ active.72 74- The following attributes are interesting:73+ This is a proxy. See :ref:`context-visibility` for more information.74 76- .. attribute:: new75+ The session object works like a dict but tracks assignment and access to its76+ keys. It cannot track modifications to mutable values, you need to set77+ :attr:`~.SessionMixin.modified` manually when modifying a list, dict, etc.78 78- ``True`` if the session is new, ``False`` otherwise.79+ .. code-block:: python80 80- .. attribute:: modified81-82- ``True`` if the session object detected a modification. Be advised83- that modifications on mutable structures are not picked up84- automatically, in that situation you have to explicitly set the85- attribute to ``True`` yourself. Here an example::86-87- # this change is not picked up because a mutable object (here88- # a list) is changed.89- session['objects'].append(42)81+ # appending to a list is not detected82+ session["numbers"].append(42)83 # so mark it as modified yourself84 session.modified = True85 93- .. attribute:: permanent86+ The session is persisted across requests using a cookie. By default the87+ users's browser will clear the cookie when it is closed. Set88+ :attr:`~.SessionMixin.permanent` to ``True`` to persist the cookie for89+ :data:`PERMANENT_SESSION_LIFETIME`.90 95- If set to ``True`` the session lives for96- :attr:`~flask.Flask.permanent_session_lifetime` seconds. The97- default is 31 days. If set to ``False`` (which is the default) the98- session will be deleted when the user closes the browser.91 100-92 Session Interface93 -----------------94 95 .. versionadded:: 0.852 unmodified lines148 another, a global variable is not good enough because it would break in149 threaded environments. Flask provides you with a special object that150 ensures it is only valid for the active request and that will return151 different values for each request. In a nutshell: it does the right161-thing, like it does for :class:`request` and :class:`session`.152+thing, like it does for :data:`.request` and :data:`.session`.153 154 .. data:: g155 165- A namespace object that can store data during an166- :doc:`application context </appcontext>`. This is an instance of167- :attr:`Flask.app_ctx_globals_class`, which defaults to168- :class:`ctx._AppCtxGlobals`.156+ A proxy to a namespace object used to store data during a single request or157+ app context. An instance of :attr:`.Flask.app_ctx_globals_class`, which158+ defaults to :class:`._AppCtxGlobals`.159 170- This is a good place to store resources during a request. For171- example, a ``before_request`` function could load a user object from172- a session id, then set ``g.user`` to be used in the view function.160+ This is a good place to store resources during a request. For example, a161+ :meth:`~.Flask.before_request` function could load a user object from a162+ session id, then set ``g.user`` to be used in the view function.163 174- This is a proxy. See :ref:`notes-on-proxies` for more information.164+ This is only available when an :doc:`app context </appcontext>` is active.165 166+ This is a proxy. See :ref:`context-visibility` for more information.167+168 .. versionchanged:: 0.10169 Bound to the application context instead of the request context.170 171 .. autoclass:: flask.ctx._AppCtxGlobals4 unmodified lines176 ----------------------------177 178 .. data:: current_app179 188- A proxy to the application handling the current request. This is189- useful to access the application without needing to import it, or if190- it can't be imported, such as when using the application factory191- pattern or in blueprints and extensions.180+ A proxy to the :class:`.Flask` application handling the current request or181+ other activity.182 193- This is only available when an194- :doc:`application context </appcontext>` is pushed. This happens195- automatically during requests and CLI commands. It can be controlled196- manually with :meth:`~flask.Flask.app_context`.183+ This is useful to access the application without needing to import it, or if184+ it can't be imported, such as when using the application factory pattern or185+ in blueprints and extensions.186 198- This is a proxy. See :ref:`notes-on-proxies` for more information.187+ This is only available when an :doc:`app context </appcontext>` is active.188 189+ This is a proxy. See :ref:`context-visibility` for more information.190+191 .. autofunction:: has_request_context192 193 .. autofunction:: copy_current_request_context194 94 unmodified lines289 290 Useful Internals291 ----------------292 302-.. autoclass:: flask.ctx.RequestContext293+.. autoclass:: flask.ctx.AppContext294 :members:295 305-.. data:: flask.globals.request_ctx296+.. data:: flask.globals.app_ctx297 307- The current :class:`~flask.ctx.RequestContext`. If a request context308- is not active, accessing attributes on this proxy will raise a309- ``RuntimeError``.298+ A proxy to the active :class:`.AppContext`.299 311- This is an internal object that is essential to how Flask handles312- requests. Accessing this should not be needed in most cases. Most313- likely you want :data:`request` and :data:`session` instead.300+ This is an internal object that is essential to how Flask handles requests.301+ Accessing this should not be needed in most cases. Most likely you want302+ :data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session` instead.303 315-.. autoclass:: flask.ctx.AppContext316- :members:304+ This is only available when a :doc:`request context </appcontext>` is305+ active.306 318-.. data:: flask.globals.app_ctx307+ This is a proxy. See :ref:`context-visibility` for more information.308 320- The current :class:`~flask.ctx.AppContext`. If an app context is not321- active, accessing attributes on this proxy will raise a322- ``RuntimeError``.309+.. class:: flask.ctx.RequestContext310 324- This is an internal object that is essential to how Flask handles325- requests. Accessing this should not be needed in most cases. Most326- likely you want :data:`current_app` and :data:`g` instead.311+ .. deprecated:: 3.2312+ Merged with :class:`AppContext`. This alias will be removed in Flask 4.0.313 314+.. data:: flask.globals.request_ctx315+316+ .. deprecated:: 3.2317+ Merged with :data:`.app_ctx`. This alias will be removed in Flask 4.0.318+319 .. autoclass:: flask.blueprints.BlueprintSetupState320 :members:321 322 .. _core-signals-list:386 unmodified linesmodified:docs/appcontext.rst+137 added-98 removed
1-.. currentmodule:: flask1+The App and Request Context2+===========================3 3-The Application Context4-=======================4+The context keeps track of data and objects during a request, CLI command, or5+other activity. Rather than passing this data around to every function, the6+:data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session` proxies7+are accessed instead.8 6-The application context keeps track of the application-level data during7-a request, CLI command, or other activity. Rather than passing the8-application around to each function, the :data:`current_app` and9-:data:`g` proxies are accessed instead.9+When handling a request, the context is referred to as the "request context"10+because it contains request data in addition to application data. Otherwise,11+such as during a CLI command, it is referred to as the "app context". During an12+app context, :data:`.current_app` and :data:`.g` are available, while during a13+request context :data:`.request` and :data:`.session` are also available.14 11-This is similar to :doc:`/reqcontext`, which keeps track of12-request-level data during a request. A corresponding application context13-is pushed when a request context is pushed.15 16 Purpose of the Context17 ----------------------18 18-The :class:`Flask` application object has attributes, such as19-:attr:`~Flask.config`, that are useful to access within views and20-:doc:`CLI commands </cli>`. However, importing the ``app`` instance21-within the modules in your project is prone to circular import issues.22-When using the :doc:`app factory pattern </patterns/appfactories>` or23-writing reusable :doc:`blueprints </blueprints>` or24-:doc:`extensions </extensions>` there won't be an ``app`` instance to25-import at all.19+The context and proxies help solve two development issues: circular imports, and20+passing around global data during a request.21 27-Flask solves this issue with the *application context*. Rather than28-referring to an ``app`` directly, you use the :data:`current_app`29-proxy, which points to the application handling the current activity.22+The :class:`.Flask` application object has attributes, such as23+:attr:`~.Flask.config`, that are useful to access within views and other24+functions. However, importing the ``app`` instance within the modules in your25+project is prone to circular import issues. When using the26+:doc:`app factory pattern </patterns/appfactories>` or writing reusable27+:doc:`blueprints </blueprints>` or :doc:`extensions </extensions>` there won't28+be an ``app`` instance to import at all.29 31-Flask automatically *pushes* an application context when handling a32-request. View functions, error handlers, and other functions that run33-during a request will have access to :data:`current_app`.30+When the application handles a request, it creates a :class:`.Request` object.31+Because a *worker* handles only one request at a time, the request data can be32+considered global to that worker during that request. Passing it as an argument33+through every function during the request becomes verbose and redundant.34 35-Flask will also automatically push an app context when running CLI36-commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.35+Flask solves these issues with the *active context* pattern. Rather than36+importing an ``app`` directly, or having to pass it and the request through to37+every single function, you import and access the proxies, which point to the38+currently active application and request data. This is sometimes referred to39+as "context local" data.40 41 39-Lifetime of the Context40------------------------42+Context During Setup43+--------------------44 42-The application context is created and destroyed as necessary. When a43-Flask application begins handling a request, it pushes an application44-context and a :doc:`request context </reqcontext>`. When the request45-ends it pops the request context then the application context.46-Typically, an application context will have the same lifetime as a47-request.45+If you try to access :data:`.current_app`, :data:`.g`, or anything that uses it,46+outside an app context, you'll get this error message:47 49-See :doc:`/reqcontext` for more information about how the contexts work50-and the full life cycle of a request.51-52-53-Manually Push a Context54------------------------55-56-If you try to access :data:`current_app`, or anything that uses it,57-outside an application context, you'll get this error message:58-48 .. code-block:: pytb49 50 RuntimeError: Working outside of application context.51 63- This typically means that you attempted to use functionality that64- needed to interface with the current application object in some way.65- To solve this, set up an application context with app.app_context().52+ Attempted to use functionality that expected a current application to be53+ set. To solve this, set up an app context using 'with app.app_context()'.54+ See the documentation on app context for more information.55 56 If you see that error while configuring your application, such as when68-initializing an extension, you can push a context manually since you69-have direct access to the ``app``. Use :meth:`~Flask.app_context` in a70-``with`` block, and everything that runs in the block will have access71-to :data:`current_app`. ::57+initializing an extension, you can push a context manually since you have direct58+access to the ``app``. Use :meth:`.Flask.app_context` in a ``with`` block.59 60+.. code-block:: python61+62 def create_app():63 app = Flask(__name__)64 65 with app.app_context():66 init_db()67 68 return app69 81-If you see that error somewhere else in your code not related to82-configuring the application, it most likely indicates that you should83-move that code into a view function or CLI command.70+If you see that error somewhere else in your code not related to setting up the71+application, it most likely indicates that you should move that code into a view72+function or CLI command.73 74 86-Storing Data87-------------75+Context During Testing76+----------------------77 89-The application context is a good place to store common data during a90-request or CLI command. Flask provides the :data:`g object <g>` for this91-purpose. It is a simple namespace object that has the same lifetime as92-an application context.78+See :doc:`/testing` for detailed information about managing the context during79+tests.80 94-.. note::95- The ``g`` name stands for "global", but that is referring to the96- data being global *within a context*. The data on ``g`` is lost97- after the context ends, and it is not an appropriate place to store98- data between requests. Use the :data:`session` or a database to99- store data across requests.81+If you try to access :data:`.request`, :data:`.session`, or anything that uses82+it, outside a request context, you'll get this error message:83 101-A common use for :data:`g` is to manage resources during a request.84+.. code-block:: pytb85 103-1. ``get_X()`` creates resource ``X`` if it does not exist, caching it104- as ``g.X``.105-2. ``teardown_X()`` closes or otherwise deallocates the resource if it106- exists. It is registered as a :meth:`~Flask.teardown_appcontext`107- handler.86+ RuntimeError: Working outside of request context.87 109-For example, you can manage a database connection using this pattern::88+ Attempted to use functionality that expected an active HTTP request. See the89+ documentation on request context for more information.90 111- from flask import g91+This will probably only happen during tests. If you see that error somewhere92+else in your code not related to testing, it most likely indicates that you93+should move that code into a view function.94 113- def get_db():114- if 'db' not in g:115- g.db = connect_to_database()95+The primary way to solve this is to use :meth:`.Flask.test_client` to simulate96+a full request.97 117- return g.db98+If you only want to unit test one function, rather than a full request, use99+:meth:`.Flask.test_request_context` in a ``with`` block.100 119- @app.teardown_appcontext120- def teardown_db(exception):121- db = g.pop('db', None)101+.. code-block:: python102 123- if db is not None:124- db.close()103+ def generate_report(year):104+ format = request.args.get("format")105+ ...106 126-During a request, every call to ``get_db()`` will return the same127-connection, and it will be closed automatically at the end of the128-request.107+ with app.test_request_context(108+ "/make_report/2017", query_string={"format": "short"}109+ ):110+ generate_report()111 130-You can use :class:`~werkzeug.local.LocalProxy` to make a new context131-local from ``get_db()``::112 133- from werkzeug.local import LocalProxy134- db = LocalProxy(get_db)113+.. _context-visibility:114 136-Accessing ``db`` will call ``get_db`` internally, in the same way that137-:data:`current_app` works.115+Visibility of the Context116+-------------------------117 118+The context will have the same lifetime as an activity, such as a request, CLI119+command, or ``with`` block. Various callbacks and signals registered with the120+app will be run during the context.121 140-Events and Signals141-------------------122+When a Flask application handles a request, it pushes a requet context123+to set the active application and request data. When it handles a CLI command,124+it pushes an app context to set the active application. When the activity ends,125+it pops that context. Proxy objects like :data:`.request`, :data:`.session`,126+:data:`.g`, and :data:`.current_app`, are accessible while the context is pushed127+and active, and are not accessible after the context is popped.128 143-The application will call functions registered with :meth:`~Flask.teardown_appcontext`144-when the application context is popped.129+The context is unique to each thread (or other worker type). The proxies cannot130+be passed to another worker, which has a different context space and will not131+know about the active context in the parent's space.132 146-The following signals are sent: :data:`appcontext_pushed`,147-:data:`appcontext_tearing_down`, and :data:`appcontext_popped`.133+Besides being scoped to each worker, the proxy object has a separate type and134+identity than the proxied real object. In some cases you'll need access to the135+real object, rather than the proxy. Use the136+:meth:`~.LocalProxy._get_current_object` method in those cases.137+138+.. code-block:: python139+140+ app = current_app._get_current_object()141+ my_signal.send(app)142+143+144+Lifcycle of the Context145+-----------------------146+147+Flask dispatches a request in multiple stages which can affect the request,148+response, and how errors are handled. See :doc:`/lifecycle` for a list of all149+the steps, callbacks, and signals during each request. The following are the150+steps directly related to the context.151+152+- The app context is pushed, the proxies are available.153+- The :data:`.appcontext_pushed` signal is sent.154+- The request is dispatched.155+- Any :meth:`.Flask.teardown_request` decorated functions are called.156+- The :data:`.request_tearing_down` signal is sent.157+- Any :meth:`.Flask.teardown_appcontext` decorated functions are called.158+- The :data:`.appcontext_tearing_down` signal is sent.159+- The app context is popped, the proxies are no longer available.160+- The :data:`.appcontext_popped` signal is sent.161+162+The teardown callbacks are called by the context when it is popped. They are163+called even if there is an unhandled exception during dispatch. They may be164+called multiple times in some test scenarios. This means there is no guarantee165+that any other parts of the request dispatch have run. Be sure to write these166+functions in a way that does not depend on other callbacks and will not fail.167+168+169+How the Context Works170+---------------------171+172+Context locals are implemented using Python's :mod:`contextvars` and Werkzeug's173+:class:`~werkzeug.local.LocalProxy`. Python's contextvars are a low level174+structure to manage data local to a thread or coroutine. ``LocalProxy`` wraps175+the contextvar so that access to any attributes and methods is forwarded to the176+object stored in the contextvar.177+178+The context is tracked like a stack, with the active context at the top of the179+stack. Flask manages pushing and popping contexts during requests, CLI commands,180+testing, ``with`` blocks, etc. The proxies access attributes on the active181+context.182+183+Because it is a stack, other contexts may be pushed to change the proxies during184+an already active context. This is not a common pattern, but can be used in185+advanced use cases. For example, a Flask application can be used as WSGI186+middleware, calling another wrapped Flask app from a view.modified:docs/design.rst+12 added-11 removed
167 unmodified lines168 infrastructure, packages with dependencies are no longer an issue and169 there are very few reasons against having libraries that depend on others.170 171 172-Thread Locals173--------------172+Context Locals173+--------------174 175-Flask uses thread local objects (context local objects in fact, they176-support greenlet contexts as well) for request, session and an extra177-object you can put your own things on (:data:`~flask.g`). Why is that and178-isn't that a bad idea?175+Flask uses special context locals and proxies to provide access to the176+current app and request data to any code running during a request, CLI command,177+etc. Context locals are specific to the worker handling the activity, such as a178+thread, process, coroutine, or greenlet.179 180-Yes it is usually not such a bright idea to use thread locals. They cause181-troubles for servers that are not based on the concept of threads and make182-large applications harder to maintain. However Flask is just not designed183-for large applications or asynchronous servers. Flask wants to make it184-quick and easy to write a traditional web application.180+The context and proxies help solve two development issues: circular imports, and181+passing around global data. :data:`.current_app: can be used to access the182+application object without needing to import the app object directly, avoiding183+circular import issues. :data:`.request`, :data:`.session`, and :data`.g` can be184+imported to access the current data for the request, rather than needing to185+pass them as arguments through every single function in your project.186 187 188 Async/await and ASGI support189 ----------------------------40 unmodified linesmodified:docs/extensiondev.rst+8 added-9 removed
65 unmodified lines66 67 It is important that the app is not stored on the extension, don't do68 ``self.app = app``. The only time the extension should have direct69 access to an app is during ``init_app``, otherwise it should use70-:data:`current_app`.70+:data:`.current_app`.71 72 This allows the extension to support the application factory pattern,73 avoids circular import issues when importing the extension instance74 elsewhere in a user's code, and makes testing with different29 unmodified lines104 105 A common pattern is to use :meth:`~Flask.before_request` to initialize106 some data or a connection at the beginning of each request, then107 :meth:`~Flask.teardown_request` to clean it up at the end. This can be108-stored on :data:`g`, discussed more below.108+stored on :data:`.g`, discussed more below.109 110 A more lazy approach is to provide a method that initializes and caches111 the data or connection. For example, a ``ext.get_db`` method could112 create a database connection the first time it's called, so that a view65 unmodified lines178 from types import SimpleNamespace179 g._hello = SimpleNamespace()180 g._hello.user_id = 2181 182-The data in ``g`` lasts for an application context. An application183-context is active when a request context is, or when a CLI command is184-run. If you're storing something that should be closed, use185-:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed186-when the application context ends. If it should only be valid during a187-request, or would not be used in the CLI outside a request, use188-:meth:`~flask.Flask.teardown_request`.182+The data in ``g`` lasts for an application context. An application context is183+active during a request, CLI command, or ``with app.app_context()`` block. If184+you're storing something that should be closed, use185+:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed when the186+app context ends. If it should only be valid during a request, or would not be187+used in the CLI outside a request, use :meth:`~flask.Flask.teardown_request`.188 189 190 Views and Models191 ----------------114 unmodified linesmodified:docs/index.rst-1 removed
50 unmodified lines51 signals52 views53 lifecycle54 appcontext55- reqcontext55 blueprints56 extensions57 cli58 server30 unmodified linesmodified:docs/lifecycle.rst+16 added-13 removed
115 unmodified lines116 the view function, and pass the return value back to the server. But there are many more117 parts that you can use to customize its behavior.118 119 #. WSGI server calls the Flask object, which calls :meth:`.Flask.wsgi_app`.120-#. A :class:`.RequestContext` object is created. This converts the WSGI ``environ``121- dict into a :class:`.Request` object. It also creates an :class:`AppContext` object.122-#. The :doc:`app context <appcontext>` is pushed, which makes :data:`.current_app` and123- :data:`.g` available.120+#. An :class:`.AppContext` object is created. This converts the WSGI ``environ``121+ dict into a :class:`.Request` object.122+#. The :doc:`app context <appcontext>` is pushed, which makes123+ :data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session`124+ available.125 #. The :data:`.appcontext_pushed` signal is sent.125-#. The :doc:`request context <reqcontext>` is pushed, which makes :attr:`.request` and126- :class:`.session` available.127-#. The session is opened, loading any existing session data using the app's128- :attr:`~.Flask.session_interface`, an instance of :class:`.SessionInterface`.126 #. The URL is matched against the URL rules registered with the :meth:`~.Flask.route`127 decorator during application setup. If there is no match, the error - usually a 404,128 405, or redirect - is stored to be handled later.129 #. The :data:`.request_started` signal is sent.7 unmodified lines137 decorated function that matches the exception class or HTTP error code, it is138 called to handle the error and return a response.139 #. Whatever returned a response value - a before request function, the view, or an140 error handler, that value is converted to a :class:`.Response` object.144-#. Any :func:`~.after_this_request` decorated functions are called, then cleared.141+#. Any :func:`~.after_this_request` decorated functions are called, which can modify142+ the response object. They are then cleared.143 #. Any :meth:`~.Flask.after_request` decorated functions are called, which can modify144 the response object.145 #. The session is saved, persisting any modified session data using the app's146 :attr:`~.Flask.session_interface`.4 unmodified lines151 The :data:`.got_request_exception` signal is sent.152 #. The response object's status, headers, and body are returned to the WSGI server.153 #. Any :meth:`~.Flask.teardown_request` decorated functions are called.154 #. The :data:`.request_tearing_down` signal is sent.157-#. The request context is popped, :attr:`.request` and :class:`.session` are no longer158- available.155 #. Any :meth:`~.Flask.teardown_appcontext` decorated functions are called.156 #. The :data:`.appcontext_tearing_down` signal is sent.161-#. The app context is popped, :data:`.current_app` and :data:`.g` are no longer162- available.157+#. The app context is popped, :data:`.current_app`, :data:`.g`, :data:`.request`,158+ and :data:`.session` are no longer available.159 #. The :data:`.appcontext_popped` signal is sent.160 161+When executing a CLI command or plain app context without request data, the same162+order of steps is followed, omitting the steps that refer to the request.163+164+A :class:`Blueprint` can add handlers for these events that are specific to the165+blueprint. The handlers for a blueprint will run if the blueprint166+owns the route that matches the request.167+168 There are even more decorators and customization points than this, but that aren't part169 of every request lifecycle. They're more specific to certain things you might use during170 a request, such as templates, building URLs, or handling JSON data. See the rest of this171 documentation, as well as the :doc:`api` to explore further.modified:docs/quickstart.rst+38 added-85 removed
256 unmodified lines257 258 For example, here we use the :meth:`~flask.Flask.test_request_context` method259 to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`260 tells Flask to behave as though it's handling a request even while we use a261-Python shell. See :ref:`context-locals`.261+Python shell. See :doc:`/appcontext`.262 263 .. code-block:: python264 265 from flask import url_for182 unmodified lines448 449 Accessing Request Data450 ----------------------451 452-For web applications it's crucial to react to the data a client sends to453-the server. In Flask this information is provided by the global454-:class:`~flask.request` object. If you have some experience with Python455-you might be wondering how that object can be global and how Flask456-manages to still be threadsafe. The answer is context locals:452+For web applications it's crucial to react to the data a client sends to the453+server. In Flask this information is provided by the global :data:`.request`454+object, which is an instance of :class:`.Request`. This object has many455+attributes and methods to work with the incoming request data, but here is a456+broad overview. First it needs to be imported.457 458+.. code-block:: python459 459-.. _context-locals:460-461-Context Locals462-``````````````463-464-.. admonition:: Insider Information465-466- If you want to understand how that works and how you can implement467- tests with context locals, read this section, otherwise just skip it.468-469-Certain objects in Flask are global objects, but not of the usual kind.470-These objects are actually proxies to objects that are local to a specific471-context. What a mouthful. But that is actually quite easy to understand.472-473-Imagine the context being the handling thread. A request comes in and the474-web server decides to spawn a new thread (or something else, the475-underlying object is capable of dealing with concurrency systems other476-than threads). When Flask starts its internal request handling it477-figures out that the current thread is the active context and binds the478-current application and the WSGI environments to that context (thread).479-It does that in an intelligent way so that one application can invoke another480-application without breaking.481-482-So what does this mean to you? Basically you can completely ignore that483-this is the case unless you are doing something like unit testing. You484-will notice that code which depends on a request object will suddenly break485-because there is no request object. The solution is creating a request486-object yourself and binding it to the context. The easiest solution for487-unit testing is to use the :meth:`~flask.Flask.test_request_context`488-context manager. In combination with the ``with`` statement it will bind a489-test request so that you can interact with it. Here is an example::490-460 from flask import request461 493- with app.test_request_context('/hello', method='POST'):494- # now you can do something with the request until the495- # end of the with block, such as basic assertions:496- assert request.path == '/hello'497- assert request.method == 'POST'462+If you have some experience with Python you might be wondering how that object463+can be global when Flask handles multiple requests at a time. The answer is464+that :data:`.request` is actually a proxy, pointing at whatever request is465+currently being handled by a given worker, which is managed interanlly by Flask466+and Python. See :doc:`/appcontext` for much more information.467 499-The other possibility is passing a whole WSGI environment to the500-:meth:`~flask.Flask.request_context` method::468+The current request method is available in the :attr:`~.Request.method`469+attribute. To access form data (data transmitted in a ``POST`` or ``PUT``470+request), use the :attr:`~flask.Request.form` attribute, which behaves like a471+dict.472 502- with app.request_context(environ):503- assert request.method == 'POST'473+.. code-block:: python474 505-The Request Object506-``````````````````507-508-The request object is documented in the API section and we will not cover509-it here in detail (see :class:`~flask.Request`). Here is a broad overview of510-some of the most common operations. First of all you have to import it from511-the ``flask`` module::512-513- from flask import request514-515-The current request method is available by using the516-:attr:`~flask.Request.method` attribute. To access form data (data517-transmitted in a ``POST`` or ``PUT`` request) you can use the518-:attr:`~flask.Request.form` attribute. Here is a full example of the two519-attributes mentioned above::520-521- @app.route('/login', methods=['POST', 'GET'])475+ @app.route("/login", methods=["GET", "POST"])476 def login():477 error = None524- if request.method == 'POST':525- if valid_login(request.form['username'],526- request.form['password']):527- return log_the_user_in(request.form['username'])478+479+ if request.method == "POST":480+ if valid_login(request.form["username"], request.form["password"]):481+ return store_login(request.form["username"])482 else:529- error = 'Invalid username/password'530- # the code below is executed if the request method531- # was GET or the credentials were invalid532- return render_template('login.html', error=error)483+ error = "Invalid username or password"484 534-What happens if the key does not exist in the ``form`` attribute? In that535-case a special :exc:`KeyError` is raised. You can catch it like a536-standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request537-error page is shown instead. So for many situations you don't have to538-deal with that problem.485+ # Executed if the request method was GET or the credentials were invalid.486+ return render_template("login.html", error=error)487 540-To access parameters submitted in the URL (``?key=value``) you can use the541-:attr:`~flask.Request.args` attribute::488+If the key does not exist in ``form``, a special :exc:`KeyError` is raised. You489+can catch it like a normal ``KeyError``, otherwise it will return a HTTP 400490+Bad Request error page. You can also use the491+:meth:`~werkzeug.datastructures.MultiDict.get` method to get a default492+instead of an error.493 543- searchword = request.args.get('key', '')494+To access parameters submitted in the URL (``?key=value``), use the495+:attr:`~.Request.args` attribute. Key errors behave the same as ``form``,496+returning a 400 response if not caught.497 545-We recommend accessing URL parameters with `get` or by catching the546-:exc:`KeyError` because users might change the URL and presenting them a 400547-bad request page in that case is not user friendly.498+.. code-block:: python499 549-For a full list of methods and attributes of the request object, head over550-to the :class:`~flask.Request` documentation.500+ searchword = request.args.get('key', '')501 502+For a full list of methods and attributes of the request object, see the503+:class:`~.Request` documentation.504 505+506 File Uploads507 ````````````508 509 You can handle uploaded files with Flask easily. Just make sure not to349 unmodified linesmodified:docs/reqcontext.rst+2 added-239 removed
1-.. currentmodule:: flask1+:orphan:2 3 The Request Context4 ===================5 6-The request context keeps track of the request-level data during a7-request. Rather than passing the request object to each function that8-runs during a request, the :data:`request` and :data:`session` proxies9-are accessed instead.10-11-This is similar to :doc:`/appcontext`, which keeps track of the12-application-level data independent of a request. A corresponding13-application context is pushed when a request context is pushed.14-15-16-Purpose of the Context17-----------------------18-19-When the :class:`Flask` application handles a request, it creates a20-:class:`Request` object based on the environment it received from the21-WSGI server. Because a *worker* (thread, process, or coroutine depending22-on the server) handles only one request at a time, the request data can23-be considered global to that worker during that request. Flask uses the24-term *context local* for this.25-26-Flask automatically *pushes* a request context when handling a request.27-View functions, error handlers, and other functions that run during a28-request will have access to the :data:`request` proxy, which points to29-the request object for the current request.30-31-32-Lifetime of the Context33------------------------34-35-When a Flask application begins handling a request, it pushes a request36-context, which also pushes an :doc:`app context </appcontext>`. When the37-request ends it pops the request context then the application context.38-39-The context is unique to each thread (or other worker type).40-:data:`request` cannot be passed to another thread, the other thread has41-a different context space and will not know about the request the parent42-thread was pointing to.43-44-Context locals are implemented using Python's :mod:`contextvars` and45-Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46-lifetime of context vars automatically, and local proxy wraps that47-low-level interface to make the data easier to work with.48-49-50-Manually Push a Context51------------------------52-53-If you try to access :data:`request`, or anything that uses it, outside54-a request context, you'll get this error message:55-56-.. code-block:: pytb57-58- RuntimeError: Working outside of request context.59-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-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", query_string={"format": "short"}77- ):78- generate_report()79-80-If you see that error somewhere else in your code not related to81-testing, it most likely indicates that you should move that code into a82-view function.83-84-For information on how to use the request context from the interactive85-Python shell, see :doc:`/shell`.86-87-88-How the Context Works89----------------------90-91-The :meth:`Flask.wsgi_app` method is called to handle each request. It92-manages the contexts during the request. Internally, the request and93-application contexts work like stacks. When contexts are pushed, the94-proxies that depend on them are available and point at information from95-the top item.96-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-104-Other contexts may be pushed to change the proxies during a request.105-While this is not a common pattern, it can be used in advanced106-applications to, for example, do internal redirects or chain different107-applications together.108-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 executed. These113-execute even if an unhandled exception occurred during dispatch.114-115-116-.. _callbacks-and-errors:117-118-Callbacks and Errors119---------------------120-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-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-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-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-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-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-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-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 Callbacks161-~~~~~~~~~~~~~~~~~~162-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-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-Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the174-contexts until the ``with`` block exits.175-176-.. code-block:: python177-178- from flask import Flask, request179-180- app = Flask(__name__)181-182- @app.route('/')183- def hello():184- print('during view')185- return 'Hello, World!'186-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() as 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 exits203-204-Signals205-~~~~~~~206-207-The following signals are sent:208-209-#. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions210- are called.211-#. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions212- are called.213-#. :data:`got_request_exception` is sent when an exception begins to be handled, but214- before an :meth:`~Flask.errorhandler` is looked up or called.215-#. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request`216- functions are called.217-218-219-.. _notes-on-proxies:220-221-Notes On Proxies222-----------------223-224-Some of the objects provided by Flask are proxies to other objects. The225-proxies are accessed in the same way for each worker thread, but226-point to the unique object bound to each worker behind the scenes as227-described on this page.228-229-Most of the time you don't have to care about that, but there are some230-exceptions where it is good to know that this object is actually a proxy:231-232-- The proxy objects cannot fake their type as the actual object types.233- If you want to perform instance checks, you have to do that on the234- object being proxied.235-- The reference to the proxied object is needed in some situations,236- such as sending :doc:`signals` or passing data to a background237- thread.238-239-If you need to access the underlying object that is proxied, use the240-:meth:`~werkzeug.local.LocalProxy._get_current_object` method::241-242- app = current_app._get_current_object()243- my_signal.send(app)6+Obsolete, see :doc:`/appcontext` instead.modified:docs/shell.rst+16 added-35 removed
1 Working with the Shell2 ======================3 4-.. versionadded:: 0.34+One of the reasons everybody loves Python is the interactive shell. It allows5+you to play around with code in real time and immediately get results back.6+Flask provides the ``flask shell`` CLI command to start an interactive Python7+shell with some setup done to make working with the Flask app easier.8 6-One of the reasons everybody loves Python is the interactive shell. It7-basically allows you to execute Python commands in real time and8-immediately get results back. Flask itself does not come with an9-interactive shell, because it does not require any specific setup upfront,10-just import your application and start playing around.9+.. code-block:: text10 12-There are however some handy helpers to make playing around in the shell a13-more pleasant experience. The main issue with interactive console14-sessions is that you're not triggering a request like a browser does which15-means that :data:`~flask.g`, :data:`~flask.request` and others are not16-available. But the code you want to test might depend on them, so what17-can you do?11+ $ flask shell12 19-This is where some helper functions come in handy. Keep in mind however20-that these functions are not only there for interactive shell usage, but21-also for unit testing and other situations that require a faked request22-context.23-24-Generally it's recommended that you read :doc:`reqcontext` first.25-26-Command Line Interface27-----------------------28-29-Starting with Flask 0.11 the recommended way to work with the shell is the30-``flask shell`` command which does a lot of this automatically for you.31-For instance the shell is automatically initialized with a loaded32-application context.33-34-For more information see :doc:`/cli`.35-13 Creating a Request Context14 --------------------------15 16+``flask shell`` pushes an app context automatically, so :data:`.current_app` and17+:data:`.g` are already available. However, there is no HTTP request being18+handled in the shell, so :data:`.request` and :data:`.session` are not yet19+available.20+21 The easiest way to create a proper request context from the shell is by22 using the :attr:`~flask.Flask.test_request_context` method which creates23 us a :class:`~flask.ctx.RequestContext`:24 25 >>> ctx = app.test_request_context()26 45-Normally you would use the ``with`` statement to make this request object46-active, but in the shell it's easier to use the47-:meth:`~flask.ctx.RequestContext.push` and48-:meth:`~flask.ctx.RequestContext.pop` methods by hand:27+Normally you would use the ``with`` statement to make this context active, but28+in the shell it's easier to call :meth:`~.RequestContext.push` and29+:meth:`~.RequestContext.pop` manually:30 31 >>> ctx.push()32 52-From that point onwards you can work with the request object until you53-call `pop`:33+From that point onwards you can work with the request object until you call34+``pop``:35 36 >>> ctx.pop()37 38 Firing Before/After Request43 unmodified linesmodified:docs/signals.rst+4 added-5 removed
142 unmodified lines143 144 Signals and Flask's Request Context145 -----------------------------------146 147-Signals fully support :doc:`reqcontext` when receiving signals.148-Context-local variables are consistently available between149-:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can150-rely on :class:`flask.g` and others as needed. Note the limitations described151-in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.147+Context-local proxies are available between :data:`~flask.request_started` and148+:data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others149+as needed. Note the limitations described in :ref:`signals-sending` and the150+:data:`~flask.request_tearing_down` signal.151 152 153 Decorator Based Signal Subscriptions154 ------------------------------------12 unmodified linesmodified:docs/testing.rst+4 added-5 removed
273 unmodified lines274 275 Tests that depend on an Active Context276 --------------------------------------277 278-You may have functions that are called from views or commands, that279-expect an active :doc:`application context </appcontext>` or280-:doc:`request context </reqcontext>` because they access ``request``,281-``session``, or ``current_app``. Rather than testing them by making a282-request or invoking the command, you can create and activate a context278+You may have functions that are called from views or commands, that expect an279+active :doc:`app context </appcontext>` because they access :data:`.request`,280+:data:`.session`, :data:`.g`, or :data:`.current_app`. Rather than testing them by281+making a request or invoking the command, you can create and activate a context282 directly.283 284 Use ``with app.app_context()`` to push an application context. For285 example, database extensions usually require an active app context to33 unmodified linesmodified:src/flask/json/__init__.py+1 added-1 removed
139 unmodified lines140 :class:`~flask.Response` object with the ``application/json``141 mimetype. A dict or list returned from a view will be converted to a142 JSON response automatically without needing to call this.143 144- This requires an active request or application context, and calls144+ This requires an active app context, and calls145 :meth:`app.json.response() <flask.json.provider.JSONProvider.response>`.146 147 In debug mode, the output is formatted with indentation to make it148 easier to read. This may also be controlled by the provider.22 unmodified linesmodified:src/flask/sansio/app.py+5 added-11 removed
175 unmodified lines176 #: 2. Add a property for lazy per-request database connectors.177 #: 3. Return None instead of AttributeError on unexpected attributes.178 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.179 #:180- #: In Flask 0.9 this property was called `request_globals_class` but it181- #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the182- #: flask.g object is now application context scoped.183- #:180 #: .. versionadded:: 0.10181+ #: Renamed from ``request_globals_class`.182 app_ctx_globals_class = _AppCtxGlobals183 184 #: The class that is used for the ``config`` attribute of this app.185 #: Defaults to :class:`~flask.Config`.635 unmodified lines821 self.jinja_env.globals[name or f.__name__] = f822 823 @setupmethod824 def teardown_appcontext(self, f: T_teardown) -> T_teardown:828- """Registers a function to be called when the application829- context is popped. The application context is typically popped830- after the request context for each request, at the end of CLI831- commands, or after a manually pushed context ends.825+ """Registers a function to be called when the app context is popped. The826+ context is popped at the end of a request, CLI command, or manual ``with``827+ block.828 829 .. code-block:: python830 831 with app.app_context():832 ...833 834 When the ``with`` block exits (or ``ctx.pop()`` is called), the835 teardown functions are called just before the app context is840- made inactive. Since a request context typically also manages an841- application context it would also be called when you pop a842- request context.836+ made inactive.837 838 When a teardown function was called because of an unhandled839 exception it will be passed an error object. If an840 :meth:`errorhandler` is registered, it will handle the exception166 unmodified linesmodified:src/flask/sansio/scaffold.py+2 added-2 removed
505 unmodified lines506 507 @setupmethod508 def teardown_request(self, f: T_teardown) -> T_teardown:509 """Register a function to be called when the request context is510- popped. Typically this happens at the end of each request, but511- contexts may be pushed manually as well during testing.510+ popped. Typically, this happens at the end of each request, but511+ contexts may be pushed manually during testing.512 513 .. code-block:: python514 515 with app.test_request_context():277 unmodified linesmodified:src/flask/app.py+70 added-106 removed
27 unmodified lines28 29 from . import cli30 from . import typing as ft31 from .ctx import AppContext32-from .ctx import RequestContext32 from .globals import _cv_app34-from .globals import _cv_request35-from .globals import current_app33 from .globals import g34 from .globals import request38-from .globals import request_ctx35 from .globals import session36 from .helpers import get_debug_flag37 from .helpers import get_flashed_messages38 from .helpers import get_load_dotenv39 from .helpers import send_from_directory40 from .sansio.app import App45-from .sansio.scaffold import _sentinel41 from .sessions import SecureCookieSessionInterface42 from .sessions import SessionInterface43 from .signals import appcontext_tearing_down44 from .signals import got_request_exception244 unmodified lines289 The default configuration is ``None`` instead of 12 hours.290 291 .. versionadded:: 0.9292 """298- value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]293+ value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]294 295 if value is None:296 return None297 213 unmodified lines511 """512 names: t.Iterable[str | None] = (None,)513 514 # A template may be rendered outside a request context.520- if request:521- names = chain(names, reversed(request.blueprints))515+ if (ctx := _cv_app.get(None)) is not None and ctx.has_request:516+ names = chain(names, reversed(ctx.request.blueprints))517 518 # The values passed to render_template take precedence. Keep a519 # copy to re-apply after all context functions.520 orig_ctx = context.copy()359 unmodified lines880 .. versionchanged:: 0.7881 This no longer does the exception handling, this code was882 moved to the new :meth:`full_dispatch_request`.883 """889- req = request_ctx.request884+ req = _cv_app.get().request885+886 if req.routing_exception is not None:887 self.raise_routing_exception(req)888 rule: Rule = req.url_rule # type: ignore[assignment]889 # if we provide automatic options for this URL and the62 unmodified lines952 behavior of ``OPTIONS`` responses.953 954 .. versionadded:: 0.7955 """960- adapter = request_ctx.url_adapter956+ adapter = _cv_app.get().url_adapter957 methods = adapter.allowed_methods() # type: ignore[union-attr]958 rv = self.response_class()959 rv.allow.update(methods)960 return rv91 unmodified lines1052 1053 .. versionadded:: 2.21054 Moved from ``flask.url_for``, which calls this method.1055 """1060- req_ctx = _cv_request.get(None)1056+ if (ctx := _cv_app.get(None)) is not None and ctx.has_request:1057+ url_adapter = ctx.url_adapter1058+ blueprint_name = ctx.request.blueprint1059 1062- if req_ctx is not None:1063- url_adapter = req_ctx.url_adapter1064- blueprint_name = req_ctx.request.blueprint1065-1060 # If the endpoint starts with "." and the request matches a1061 # blueprint, the endpoint is relative to the blueprint.1062 if endpoint[:1] == ".":1063 if blueprint_name is not None:5 unmodified lines1069 # domain by default, unless a scheme is given.1070 if _external is None:1071 _external = _scheme is not None1072 else:1079- app_ctx = _cv_app.get(None)1080-1073 # If called by helpers.url_for, an app context is active,1074 # use its url_adapter. Otherwise, app.url_for was called1075 # directly, build an adapter.1084- if app_ctx is not None:1085- url_adapter = app_ctx.url_adapter1076+ if ctx is not None:1077+ url_adapter = ctx.url_adapter1078 else:1079 url_adapter = self.create_url_adapter(None)1080 1081 if url_adapter is None:187 unmodified lines1269 If any :meth:`before_request` handler returns a non-None value, the1270 value is handled as if it was the return value from the view, and1271 further request handling is stopped.1272 """1273+ req = _cv_app.get().request1281- names = (None, *reversed(request.blueprints))1274+ names = (None, *reversed(req.blueprints))1275 1276 for name in names:1277 if name in self.url_value_preprocessors:1278 for url_func in self.url_value_preprocessors[name]:1286- url_func(request.endpoint, request.view_args)1279+ url_func(req.endpoint, req.view_args)1280 1281 for name in names:1282 if name in self.before_request_funcs:1283 for before_func in self.before_request_funcs[name]:16 unmodified lines1300 :param response: a :attr:`response_class` object.1301 :return: a new response object or the same, has to be an1302 instance of :attr:`response_class`.1303 """1311- ctx = request_ctx._get_current_object() # type: ignore[attr-defined]1304+ ctx = _cv_app.get()1305 1306 for func in ctx._after_request_functions:1307 response = self.ensure_sync(func)(response)1308 1316- for name in chain(request.blueprints, (None,)):1309+ for name in chain(ctx.request.blueprints, (None,)):1310 if name in self.after_request_funcs:1311 for func in reversed(self.after_request_funcs[name]):1312 response = self.ensure_sync(func)(response)1313 1 unmodified line1315 self.session_interface.save_session(self, ctx.session, response)1316 1317 return response1318 1326- def do_teardown_request(1327- self,1328- exc: BaseException | None = _sentinel, # type: ignore[assignment]1329- ) -> None:1330- """Called after the request is dispatched and the response is1331- returned, right before the request context is popped.1319+ def do_teardown_request(self, exc: BaseException | None = None) -> None:1320+ """Called after the request is dispatched and the response is finalized,1321+ right before the request context is popped. Called by1322+ :meth:`.AppContext.pop`.1323 1333- This calls all functions decorated with1334- :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`1335- if a blueprint handled the request. Finally, the1336- :data:`request_tearing_down` signal is sent.1324+ This calls all functions decorated with :meth:`teardown_request`, and1325+ :meth:`Blueprint.teardown_request` if a blueprint handled the request.1326+ Finally, the :data:`request_tearing_down` signal is sent.1327 1338- This is called by1339- :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,1340- which may be delayed during testing to maintain access to1341- resources.1328+ :param exc: An unhandled exception raised while dispatching the request.1329+ Passed to each teardown function.1330 1343- :param exc: An unhandled exception raised while dispatching the1344- request. Detected from the current exception information if1345- not passed. Passed to each teardown function.1346-1331 .. versionchanged:: 0.91332 Added the ``exc`` argument.1333 """1350- if exc is _sentinel:1351- exc = sys.exc_info()[1]1334+ req = _cv_app.get().request1335 1353- for name in chain(request.blueprints, (None,)):1336+ for name in chain(req.blueprints, (None,)):1337 if name in self.teardown_request_funcs:1338 for func in reversed(self.teardown_request_funcs[name]):1339 self.ensure_sync(func)(exc)1340 1341 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1342 1360- def do_teardown_appcontext(1361- self,1362- exc: BaseException | None = _sentinel, # type: ignore[assignment]1363- ) -> None:1364- """Called right before the application context is popped.1343+ def do_teardown_appcontext(self, exc: BaseException | None = None) -> None:1344+ """Called right before the application context is popped. Called by1345+ :meth:`.AppContext.pop`.1346 1366- When handling a request, the application context is popped1367- after the request context. See :meth:`do_teardown_request`.1347+ This calls all functions decorated with :meth:`teardown_appcontext`.1348+ Then the :data:`appcontext_tearing_down` signal is sent.1349 1369- This calls all functions decorated with1370- :meth:`teardown_appcontext`. Then the1371- :data:`appcontext_tearing_down` signal is sent.1350+ :param exc: An unhandled exception raised while the context was active.1351+ Passed to each teardown function.1352 1373- This is called by1374- :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.1375-1353 .. versionadded:: 0.91354 """1378- if exc is _sentinel:1379- exc = sys.exc_info()[1]1380-1355 for func in reversed(self.teardown_appcontext_funcs):1356 self.ensure_sync(func)(exc)1357 1358 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1359 1360 def app_context(self) -> AppContext:1387- """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``1388- block to push the context, which will make :data:`current_app`1389- point at this application.1361+ """Create an :class:`.AppContext`. When the context is pushed,1362+ :data:`.current_app` and :data:`.g` become available.1363 1391- An application context is automatically pushed by1392- :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`1393- when handling a request, and when running a CLI command. Use1394- this to manually create a context outside of these situations.1364+ A context is automatically pushed when handling each request, and when1365+ running any ``flask`` CLI command. Use this as a ``with`` block to1366+ manually push a context outside of those situations, such as during1367+ setup or testing.1368 1396- ::1369+ .. code-block:: python1370 1371 with app.app_context():1372 init_db()1373 2 unmodified lines1376 .. versionadded:: 0.91377 """1378 return AppContext(self)1379 1407- def request_context(self, environ: WSGIEnvironment) -> RequestContext:1408- """Create a :class:`~flask.ctx.RequestContext` representing a1409- WSGI environment. Use a ``with`` block to push the context,1410- which will make :data:`request` point at this request.1380+ def request_context(self, environ: WSGIEnvironment) -> AppContext:1381+ """Create an :class:`.AppContext` with request information representing1382+ the given WSGI environment. A context is automatically pushed when1383+ handling each request. When the context is pushed, :data:`.request`,1384+ :data:`.session`, :data:`g:, and :data:`.current_app` become available.1385 1412- See :doc:`/reqcontext`.1386+ This method should not be used in your own code. Creating a valid WSGI1387+ environ is not trivial. Use :meth:`test_request_context` to correctly1388+ create a WSGI environ and request context instead.1389 1414- Typically you should not call this from your own code. A request1415- context is automatically pushed by the :meth:`wsgi_app` when1416- handling a request. Use :meth:`test_request_context` to create1417- an environment and context instead of this method.1390+ See :doc:`/appcontext`.1391 1419- :param environ: a WSGI environment1392+ :param environ: A WSGI environment.1393 """1421- return RequestContext(self, environ)1394+ return AppContext.from_environ(self, environ)1395 1423- def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:1424- """Create a :class:`~flask.ctx.RequestContext` for a WSGI1425- environment created from the given values. This is mostly useful1426- during testing, where you may want to run a function that uses1427- request data without dispatching a full request.1396+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext:1397+ """Create an :class:`.AppContext` with request information created from1398+ the given arguments. When the context is pushed, :data:`.request`,1399+ :data:`.session`, :data:`g:, and :data:`.current_app` become available.1400 1429- See :doc:`/reqcontext`.1401+ This is useful during testing to run a function that uses request data1402+ without dispatching a full request. Use this as a ``with`` block to push1403+ a context.1404 1431- Use a ``with`` block to push the context, which will make1432- :data:`request` point at the request for the created1433- environment. ::1405+ .. code-block:: python1406 1407 with app.test_request_context(...):1408 generate_report()1409 1438- When using the shell, it may be easier to push and pop the1439- context manually to avoid indentation. ::1410+ See :doc:`/appcontext`.1411 1441- ctx = app.test_request_context(...)1442- ctx.push()1443- ...1444- ctx.pop()1445-1412 Takes the same arguments as Werkzeug's1413 :class:`~werkzeug.test.EnvironBuilder`, with some defaults from1414 the application. See the linked Werkzeug docs for most of the1415 available arguments. Flask-specific behavior is listed here.1416 1417 :param path: URL path being requested.1418 :param base_url: Base URL where the app is being served, which1419 ``path`` is relative to. If not given, built from1454- :data:`PREFERRED_URL_SCHEME`, ``subdomain``,1455- :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.1456- :param subdomain: Subdomain name to append to1457- :data:`SERVER_NAME`.1420+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`,1421+ and :data:`APPLICATION_ROOT`.1422+ :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`.1423 :param url_scheme: Scheme to use instead of1424 :data:`PREFERRED_URL_SCHEME`.1460- :param data: The request body, either as a string or a dict of1461- form keys and values.1425+ :param data: The request body text or bytes,or a dict of form data.1426 :param json: If given, this is serialized as JSON and passed as1427 ``data``. Also defaults ``content_type`` to1428 ``application/json``.1465- :param args: other positional arguments passed to1429+ :param args: Other positional arguments passed to1430 :class:`~werkzeug.test.EnvironBuilder`.1467- :param kwargs: other keyword arguments passed to1431+ :param kwargs: Other keyword arguments passed to1432 :class:`~werkzeug.test.EnvironBuilder`.1433 """1434 from .testing import EnvironBuilder1435 1436 builder = EnvironBuilder(self, *args, **kwargs)1437 1438 try:1475- return self.request_context(builder.get_environ())1439+ environ = builder.get_environ()1440 finally:1441 builder.close()1442 1443+ return self.request_context(environ)1444+1445 def wsgi_app(1446 self, environ: WSGIEnvironment, start_response: StartResponse1447 ) -> cabc.Iterable[bytes]:1448 """The actual WSGI application. This is not implemented in12 unmodified lines1461 .. versionchanged:: 0.71462 Teardown events for the request and app contexts are called1463 even if an unhandled error occurs. Other events may not be1464 called depending on when an error occurs during dispatch.1499- See :ref:`callbacks-and-errors`.1465 1466 :param environ: A WSGI environment.1467 :param start_response: A callable accepting a status code,1468 a list of headers, and an optional exception context to14 unmodified lines1483 return response(environ, start_response)1484 finally:1485 if "werkzeug.debug.preserve_context" in environ:1486 environ["werkzeug.debug.preserve_context"](_cv_app.get())1522- environ["werkzeug.debug.preserve_context"](_cv_request.get())1487 1488 if error is not None and self.should_ignore_error(error):1489 error = None1490 10 unmodified linesmodified:src/flask/cli.py+1 added-1 removed
626 unmodified lines627 628 # Push an app context for the loaded app unless it is already629 # active somehow. This makes the context available to parameter630 # and command callbacks without needing @with_appcontext.631- if not current_app or current_app._get_current_object() is not app: # type: ignore[attr-defined]631+ if not current_app or current_app._get_current_object() is not app:632 ctx.with_resource(app.app_context())633 634 return app.cli.get_command(ctx, name)635 492 unmodified linesmodified:src/flask/ctx.py+261 added-194 removed
1 from __future__ import annotations2 3 import contextvars4-import sys4 import typing as t5 from functools import update_wrapper6 from types import TracebackType7 8 from werkzeug.exceptions import HTTPException9+from werkzeug.routing import MapAdapter10 11 from . import typing as ft12 from .globals import _cv_app13-from .globals import _cv_request13 from .signals import appcontext_popped14 from .signals import appcontext_pushed15 17-if t.TYPE_CHECKING: # pragma: no cover16+if t.TYPE_CHECKING:17+ import typing_extensions as te18 from _typeshed.wsgi import WSGIEnvironment19 20 from .app import Flask21 from .sessions import SessionMixin8 unmodified lines30 """A plain object. Used as a namespace for storing data during an31 application context.32 33 Creating an app context automatically creates this object, which is34- made available as the :data:`g` proxy.34+ made available as the :data:`.g` proxy.35 36 .. describe:: 'key' in g37 38 Check whether an attribute is present.77 unmodified lines116 117 def after_this_request(118 f: ft.AfterRequestCallable[t.Any],119 ) -> ft.AfterRequestCallable[t.Any]:120- """Executes a function after this request. This is useful to modify121- response objects. The function is passed the response object and has122- to return the same or a new one.120+ """Decorate a function to run after the current request. The behavior is the121+ same as :meth:`.Flask.after_request`, except it only applies to the current122+ request, rather than every request. Therefore, it must be used within a123+ request context, rather than during setup.124 124- Example::125+ .. code-block:: python126 126- @app.route('/')127+ @app.route("/")128 def index():129 @after_this_request130 def add_header(response):130- response.headers['X-Foo'] = 'Parachute'131+ response.headers["X-Foo"] = "Parachute"132 return response132- return 'Hello World!'133 134- This is more useful if a function other than the view function wants to135- modify a response. For instance think of a decorator that wants to add136- some headers without converting the return value into a response object.134+ return "Hello, World!"135 136 .. versionadded:: 0.9137 """140- ctx = _cv_request.get(None)138+ ctx = _cv_app.get(None)139 142- if ctx is None:140+ if ctx is None or not ctx.has_request:141 raise RuntimeError(142 "'after_this_request' can only be used when a request"143 " context is active, such as in a view function."144 )5 unmodified lines150 F = t.TypeVar("F", bound=t.Callable[..., t.Any])151 152 153 def copy_current_request_context(f: F) -> F:156- """A helper function that decorates a function to retain the current157- request context. This is useful when working with greenlets. The moment158- the function is decorated a copy of the request context is created and159- then pushed when the function is called. The current session is also160- included in the copied request context.154+ """Decorate a function to run inside the current request context. This can155+ be used when starting a background task, otherwise it will not see the app156+ and request objects that were active in the parent.157 162- Example::158+ .. warning::159 160+ Due to the following caveats, it is often safer (and simpler) to pass161+ the data you need when starting the task, rather than using this and162+ relying on the context objects.163+164+ In order to avoid execution switching partially though reading data, either165+ read the request body (access ``form``, ``json``, ``data``, etc) before166+ starting the task, or use a lock. This can be an issue when using threading,167+ but shouldn't be an issue when using greenlet/gevent or asyncio.168+169+ If the task will access ``session``, be sure to do so in the parent as well170+ so that the ``Vary: cookie`` header will be set. Modifying ``session`` in171+ the task should be avoided, as it may execute after the response cookie has172+ already been written.173+174+ .. code-block:: python175+176 import gevent177 from flask import copy_current_request_context178 179 @app.route('/')7 unmodified lines187 return 'Regular response'188 189 .. versionadded:: 0.10190 """179- ctx = _cv_request.get(None)191+ ctx = _cv_app.get(None)192 193 if ctx is None:194 raise RuntimeError(195 "'copy_current_request_context' can only be used when a"9 unmodified lines205 return update_wrapper(wrapper, f) # type: ignore[return-value]206 207 208 def has_request_context() -> bool:197- """If you have code that wants to test if a request context is there or198- not this function can be used. For instance, you may want to take advantage199- of request information if the request object is available, but fail200- silently if it is unavailable.209+ """Test if an app context is active and if it has request information.210 202- ::211+ .. code-block:: python212 204- class User(db.Model):213+ from flask import has_request_context, request214 206- def __init__(self, username, remote_addr=None):207- self.username = username208- if remote_addr is None and has_request_context():209- remote_addr = request.remote_addr215+ if has_request_context():216+ remote_addr = request.remote_addr210- self.remote_addr = remote_addr217 212- Alternatively you can also just test any of the context bound objects213- (such as :class:`request` or :class:`g`) for truthness::218+ If a request context is active, the :data:`.request` and :data:`.session`219+ context proxies will available and ``True``, otherwise ``False``. You can220+ use that to test the data you use, rather than using this function.221 215- class User(db.Model):222+ .. code-block:: python223 217- def __init__(self, username, remote_addr=None):218- self.username = username219- if remote_addr is None and request:220- remote_addr = request.remote_addr221- self.remote_addr = remote_addr224+ from flask import request225 226+ if request:227+ remote_addr = request.remote_addr228+229 .. versionadded:: 0.7230 """225- return _cv_request.get(None) is not None231+ return (ctx := _cv_app.get(None)) is not None and ctx.has_request232 233 234 def has_app_context() -> bool:229- """Works like :func:`has_request_context` but for the application230- context. You can also just do a boolean check on the231- :data:`current_app` object instead.235+ """Test if an app context is active. Unlike :func:`has_request_context`236+ this can be true outside a request, such as in a CLI command.237 233- .. versionadded:: 0.9234- """235- return _cv_app.get(None) is not None238+ .. code-block:: python239 240+ from flask import has_app_context, g241 238-class AppContext:239- """The app context contains application-specific information. An app240- context is created and pushed at the beginning of each request if241- one is not already active. An app context is also pushed when242- running CLI commands.243- """242+ if has_app_context():243+ g.cached_data = ...244 245- def __init__(self, app: Flask) -> None:246- self.app = app247- self.url_adapter = app.create_url_adapter(None)248- self.g: _AppCtxGlobals = app.app_ctx_globals_class()249- self._cv_tokens: list[contextvars.Token[AppContext]] = []245+ If an app context is active, the :data:`.g` and :data:`.current_app` context246+ proxies will available and ``True``, otherwise ``False``. You can use that247+ to test the data you use, rather than using this function.248 251- def push(self) -> None:252- """Binds the app context to the current context."""253- self._cv_tokens.append(_cv_app.set(self))254- appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)249+ from flask import g250 256- def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore257- """Pops the app context."""258- try:259- if len(self._cv_tokens) == 1:260- if exc is _sentinel:261- exc = sys.exc_info()[1]262- self.app.do_teardown_appcontext(exc)263- finally:264- ctx = _cv_app.get()265- _cv_app.reset(self._cv_tokens.pop())251+ if g:252+ g.cached_data = ...253 267- if ctx is not self:268- raise AssertionError(269- f"Popped wrong app context. ({ctx!r} instead of {self!r})"270- )254+ .. versionadded:: 0.9255+ """256+ return _cv_app.get(None) is not None257 272- appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)258 274- def __enter__(self) -> AppContext:275- self.push()276- return self259+class AppContext:260+ """An app context contains information about an app, and about the request261+ when handling a request. A context is pushed at the beginning of each262+ request and CLI command, and popped at the end. The context is referred to263+ as a "request context" if it has request information, and an "app context"264+ if not.265 278- def __exit__(279- self,280- exc_type: type | None,281- exc_value: BaseException | None,282- tb: TracebackType | None,283- ) -> None:284- self.pop(exc_value)266+ Do not use this class directly. Use :meth:`.Flask.app_context` to create an267+ app context if needed during setup, and :meth:`.Flask.test_request_context`268+ to create a request context if needed during tests.269 270+ When the context is popped, it will evaluate all the teardown functions271+ registered with :meth:`~flask.Flask.teardown_request` (if handling a272+ request) then :meth:`.Flask.teardown_appcontext`.273 287-class RequestContext:288- """The request context contains per-request information. The Flask289- app creates and pushes it at the beginning of the request, then pops290- it at the end of the request. It will create the URL adapter and291- request object for the WSGI environment provided.274+ When using the interactive debugger, the context will be restored so275+ ``request`` is still accessible. Similarly, the test client can preserve the276+ context after the request ends. However, teardown functions may already have277+ closed some resources such as database connections, and will run again when278+ the restored context is popped.279 293- Do not attempt to use this class directly, instead use294- :meth:`~flask.Flask.test_request_context` and295- :meth:`~flask.Flask.request_context` to create this object.280+ :param app: The application this context represents.281+ :param request: The request data this context represents.282+ :param session: The session data this context represents. If not given,283+ loaded from the request on first access.284 297- When the request context is popped, it will evaluate all the298- functions registered on the application for teardown execution299- (:meth:`~flask.Flask.teardown_request`).285+ .. versionchanged:: 3.2286+ Merged with ``RequestContext``. The ``RequestContext`` alias will be287+ removed in Flask 4.0.288 301- The request context is automatically popped at the end of the302- request. When using the interactive debugger, the context will be303- restored so ``request`` is still accessible. Similarly, the test304- client can preserve the context after the request ends. However,305- teardown functions may already have closed some resources such as306- database connections.289+ .. versionchanged:: 3.2290+ A combined app and request context is pushed for every request and CLI291+ command, rather than trying to detect if an app context is already292+ pushed.293+294+ .. versionchanged:: 3.2295+ The session is loaded the first time it is accessed, rather than when296+ the context is pushed.297 """298 299 def __init__(300 self,301 app: Flask,312- environ: WSGIEnvironment,302+ *,303 request: Request | None = None,304 session: SessionMixin | None = None,305 ) -> None:306 self.app = app317- if request is None:318- request = app.request_class(environ)319- request.json_module = app.json320- self.request: Request = request321- self.url_adapter = None307+ """The application represented by this context. Accessed through308+ :data:`.current_app`.309+ """310+311+ self.g: _AppCtxGlobals = app.app_ctx_globals_class()312+ """The global data for this context. Accessed through :data:`.g`."""313+314+ self.url_adapter: MapAdapter | None = None315+ """The URL adapter bound to the request, or the app if not in a request.316+ May be ``None`` if binding failed.317+ """318+319+ self._request: Request | None = request320+ self._session: SessionMixin | None = session321+ self._flashes: list[tuple[str, str]] | None = None322+ self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []323+324 try:323- self.url_adapter = app.create_url_adapter(self.request)325+ self.url_adapter = app.create_url_adapter(self._request)326 except HTTPException as e:325- self.request.routing_exception = e326- self.flashes: list[tuple[str, str]] | None = None327- self.session: SessionMixin | None = session328- # Functions that should be executed after the request on the response329- # object. These will be called before the regular "after_request"330- # functions.331- self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []327+ if self._request is not None:328+ self._request.routing_exception = e329 333- self._cv_tokens: list[334- tuple[contextvars.Token[RequestContext], AppContext | None]335- ] = []330+ self._cv_token: contextvars.Token[AppContext] | None = None331+ """The previous state to restore when popping."""332 337- def copy(self) -> RequestContext:338- """Creates a copy of this request context with the same request object.339- This can be used to move a request context to a different greenlet.340- Because the actual request object is the same this cannot be used to341- move a request context to a different thread unless access to the342- request object is locked.333+ self._push_count: int = 0334+ """Track nested pushes of this context. Cleanup will only run once the335+ original push has been popped.336+ """337 344- .. versionadded:: 0.10338+ @classmethod339+ def from_environ(cls, app: Flask, environ: WSGIEnvironment, /) -> te.Self:340+ """Create an app context with request data from the given WSGI environ.341 342+ :param app: The application this context represents.343+ :param environ: The request data this context represents.344+ """345+ request = app.request_class(environ)346+ request.json_module = app.json347+ return cls(app, request=request)348+349+ @property350+ def has_request(self) -> bool:351+ """True if this context was created with request data."""352+ return self._request is not None353+354+ def copy(self) -> te.Self:355+ """Create a new context with the same data objects as this context. See356+ :func:`.copy_current_request_context`.357+358 .. versionchanged:: 1.1347- The current session object is used instead of reloading the original348- data. This prevents `flask.session` pointing to an out-of-date object.359+ The current session data is used instead of reloading the original data.360+361+ .. versionadded:: 0.10362 """363 return self.__class__(364 self.app,352- environ=self.request.environ,353- request=self.request,354- session=self.session,365+ request=self._request,366+ session=self._session,367 )368 369+ @property370+ def request(self) -> Request:371+ """The request object associated with this context. Accessed through372+ :data:`.request`. Only available in request contexts, otherwise raises373+ :exc:`RuntimeError`.374+ """375+ if self._request is None:376+ raise RuntimeError("There is no request in this context.")377+378+ return self._request379+380+ @property381+ def session(self) -> SessionMixin:382+ """The session object associated with this context. Accessed through383+ :data:`.session`. Only available in request contexts, otherwise raises384+ :exc:`RuntimeError`.385+ """386+ if self._request is None:387+ raise RuntimeError("There is no request in this context.")388+389+ if self._session is None:390+ si = self.app.session_interface391+ self._session = si.open_session(self.app, self.request)392+393+ if self._session is None:394+ self._session = si.make_null_session(self.app)395+396+ return self._session397+398 def match_request(self) -> None:358- """Can be overridden by a subclass to hook into the matching359- of the request.399+ """Apply routing to the current request, storing either the matched400+ endpoint and args, or a routing exception.401 """402 try:362- result = self.url_adapter.match(return_rule=True) # type: ignore363- self.request.url_rule, self.request.view_args = result # type: ignore403+ result = self.url_adapter.match(return_rule=True) # type: ignore[union-attr]404 except HTTPException as e:365- self.request.routing_exception = e405+ self._request.routing_exception = e # type: ignore[union-attr]406+ else:407+ self._request.url_rule, self._request.view_args = result # type: ignore[union-attr]408 409 def push(self) -> None:368- # Before we push the request context we have to ensure that there369- # is an application context.370- app_ctx = _cv_app.get(None)410+ """Push this context so that it is the active context. If this is a411+ request context, calls :meth:`match_request` to perform routing with412+ the context active.413 372- if app_ctx is None or app_ctx.app is not self.app:373- app_ctx = self.app.app_context()374- app_ctx.push()375- else:376- app_ctx = None414+ Typically, this is not used directly. Instead, use a ``with`` block415+ to manage the context.416 378- self._cv_tokens.append((_cv_request.set(self), app_ctx))417+ In some situations, such as streaming or testing, the context may be418+ pushed multiple times. It will only trigger matching and signals if it419+ is not currently pushed.420+ """421+ self._push_count += 1422 380- # Open the session at the moment that the request context is available.381- # This allows a custom open_session method to use the request context.382- # Only open a new session if this is the first time the request was383- # pushed, otherwise stream_with_context loses the session.384- if self.session is None:385- session_interface = self.app.session_interface386- self.session = session_interface.open_session(self.app, self.request)423+ if self._cv_token is not None:424+ return425 388- if self.session is None:389- self.session = session_interface.make_null_session(self.app)426+ self._cv_token = _cv_app.set(self)427+ appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)428 391- # Match the request URL after loading the session, so that the392- # session is available in custom URL converters.393- if self.url_adapter is not None:429+ if self._request is not None and self.url_adapter is not None:430 self.match_request()431 396- def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore397- """Pops the request context and unbinds it by doing that. This will398- also trigger the execution of functions registered by the399- :meth:`~flask.Flask.teardown_request` decorator.432+ def pop(self, exc: BaseException | None = None) -> None:433+ """Pop this context so that it is no longer the active context. Then434+ call teardown functions and signals.435 436+ Typically, this is not used directly. Instead, use a ``with`` block437+ to manage the context.438+439+ This context must currently be the active context, otherwise a440+ :exc:`RuntimeError` is raised. In some situations, such as streaming or441+ testing, the context may have been pushed multiple times. It will only442+ trigger cleanup once it has been popped as many times as it was pushed.443+ Until then, it will remain the active context.444+445+ :param exc: An unhandled exception that was raised while the context was446+ active. Passed to teardown functions.447+448 .. versionchanged:: 0.9402- Added the `exc` argument.449+ Added the ``exc`` argument.450 """404- clear_request = len(self._cv_tokens) == 1451+ if self._cv_token is None:452+ raise RuntimeError(f"Cannot pop this context ({self!r}), it is not pushed.")453 406- try:407- if clear_request:408- if exc is _sentinel:409- exc = sys.exc_info()[1]410- self.app.do_teardown_request(exc)454+ ctx = _cv_app.get(None)455 412- request_close = getattr(self.request, "close", None)413- if request_close is not None:414- request_close()415- finally:416- ctx = _cv_request.get()417- token, app_ctx = self._cv_tokens.pop()418- _cv_request.reset(token)456+ if ctx is None or self._cv_token is None:457+ raise RuntimeError(458+ f"Cannot pop this context ({self!r}), there is no active context."459+ )460 420- # get rid of circular dependencies at the end of the request421- # so that we don't require the GC to be active.422- if clear_request:423- ctx.request.environ["werkzeug.request"] = None461+ if ctx is not self:462+ raise RuntimeError(463+ f"Cannot pop this context ({self!r}), it is not the active"464+ f" context ({ctx!r})."465+ )466 425- if app_ctx is not None:426- app_ctx.pop(exc)467+ self._push_count -= 1468 428- if ctx is not self:429- raise AssertionError(430- f"Popped wrong request context. ({ctx!r} instead of {self!r})"431- )469+ if self._push_count > 0:470+ return471 472+ try:473+ if self._request is not None:474+ self.app.do_teardown_request(exc)475+ self._request.close()476+ finally:477+ self.app.do_teardown_appcontext(exc)478+ _cv_app.reset(self._cv_token)479+ self._cv_token = None480+ appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)481+433- def __enter__(self) -> RequestContext:482+ def __enter__(self) -> te.Self:483 self.push()484 return self485 486 def __exit__(487 self,439- exc_type: type | None,488+ exc_type: type[BaseException] | None,489 exc_value: BaseException | None,490 tb: TracebackType | None,491 ) -> None:492 self.pop(exc_value)493 494 def __repr__(self) -> str:495+ if self._request is not None:446- return (447- f"<{type(self).__name__} {self.request.url!r}"448- f" [{self.request.method}] of {self.app.name}>"496+ return (497+ f"<{type(self).__name__} {id(self)} of {self.app.name},"498+ f" {self.request.method} {self.request.url!r}>"499+ )500+501+ return f"<{type(self).__name__} {id(self)} of {self.app.name}>"502+503+504+def __getattr__(name: str) -> t.Any:505+ import warnings506+507+ if name == "RequestContext":508+ warnings.warn(509+ "'RequestContext' has merged with 'AppContext', and will be removed"510+ " in Flask 4.0. Use 'AppContext' instead.",511+ DeprecationWarning,512+ stacklevel=2,513 )514+ return AppContext515+516+ raise AttributeError(name)modified:src/flask/debughelpers.py+4 added-3 removed
4 unmodified lines5 from jinja2.loaders import BaseLoader6 from werkzeug.routing import RequestRedirect7 8 from .blueprints import Blueprint9-from .globals import request_ctx9+from .globals import _cv_app10 from .sansio.app import App11 12 if t.TYPE_CHECKING:13 from .sansio.scaffold import Scaffold121 unmodified lines135 """This should help developers understand what failed"""136 info = [f"Locating template {template!r}:"]137 total_found = 0138 blueprint = None139- if request_ctx and request_ctx.request.blueprint is not None:140- blueprint = request_ctx.request.blueprint139 140+ if (ctx := _cv_app.get(None)) is not None and ctx.has_request:141+ blueprint = ctx.request.blueprint142+143 for idx, (loader, srcobj, triple) in enumerate(attempts):144 if isinstance(srcobj, App):145 src_info = f"application {srcobj.import_name!r}"146 elif isinstance(srcobj, Blueprint):33 unmodified linesmodified:src/flask/globals.py+44 added-18 removed
7 unmodified lines8 if t.TYPE_CHECKING: # pragma: no cover9 from .app import Flask10 from .ctx import _AppCtxGlobals11 from .ctx import AppContext12- from .ctx import RequestContext12 from .sessions import SessionMixin13 from .wrappers import Request14 15+ T = t.TypeVar("T", covariant=True)16 17+ class ProxyMixin(t.Protocol[T]):18+ def _get_current_object(self) -> T: ...19+20+ # These subclasses inform type checkers that the proxy objects look like the21+ # proxied type along with the _get_current_object method.22+ class FlaskProxy(ProxyMixin[Flask], Flask): ...23+24+ class AppContextProxy(ProxyMixin[AppContext], AppContext): ...25+26+ class _AppCtxGlobalsProxy(ProxyMixin[_AppCtxGlobals], _AppCtxGlobals): ...27+28+ class RequestProxy(ProxyMixin[Request], Request): ...29+30+ class SessionMixinProxy(ProxyMixin[SessionMixin], SessionMixin): ...31+32+33 _no_app_msg = """\34 Working outside of application context.35 20-This typically means that you attempted to use functionality that needed21-the current application. To solve this, set up an application context22-with app.app_context(). See the documentation for more information.\36+Attempted to use functionality that expected a current application to be set. To37+solve this, set up an app context using 'with app.app_context()'. See the38+documentation on app context for more information.\39 """40 _cv_app: ContextVar[AppContext] = ContextVar("flask.app_ctx")25-app_ctx: AppContext = LocalProxy( # type: ignore[assignment]41+app_ctx: AppContextProxy = LocalProxy( # type: ignore[assignment]42 _cv_app, unbound_message=_no_app_msg43 )28-current_app: Flask = LocalProxy( # type: ignore[assignment]44+current_app: FlaskProxy = LocalProxy( # type: ignore[assignment]45 _cv_app, "app", unbound_message=_no_app_msg46 )31-g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment]47+g: _AppCtxGlobalsProxy = LocalProxy( # type: ignore[assignment]48 _cv_app, "g", unbound_message=_no_app_msg49 )50 51 _no_req_msg = """\52 Working outside of request context.53 38-This typically means that you attempted to use functionality that needed39-an active HTTP request. Consult the documentation on testing for40-information about how to avoid this problem.\54+Attempted to use functionality that expected an active HTTP request. See the55+documentation on request context for more information.\56 """42-_cv_request: ContextVar[RequestContext] = ContextVar("flask.request_ctx")43-request_ctx: RequestContext = LocalProxy( # type: ignore[assignment]44- _cv_request, unbound_message=_no_req_msg57+request: RequestProxy = LocalProxy( # type: ignore[assignment]58+ _cv_app, "request", unbound_message=_no_req_msg59 )46-request: Request = LocalProxy( # type: ignore[assignment]47- _cv_request, "request", unbound_message=_no_req_msg60+session: SessionMixinProxy = LocalProxy( # type: ignore[assignment]61+ _cv_app, "session", unbound_message=_no_req_msg62 )49-session: SessionMixin = LocalProxy( # type: ignore[assignment]50- _cv_request, "session", unbound_message=_no_req_msg51-)63+64+65+def __getattr__(name: str) -> t.Any:66+ import warnings67+68+ if name == "request_ctx":69+ warnings.warn(70+ "'request_ctx' has merged with 'app_ctx', and will be removed"71+ " in Flask 4.0. Use 'app_ctx' instead.",72+ DeprecationWarning,73+ stacklevel=2,74+ )75+ return app_ctx76+77+ raise AttributeError(name)modified:src/flask/helpers.py+22 added-28 removed
12 unmodified lines13 from werkzeug.utils import redirect as _wz_redirect14 from werkzeug.wrappers import Response as BaseResponse15 16 from .globals import _cv_app17-from .globals import _cv_request17+from .globals import app_ctx18 from .globals import current_app19 from .globals import request20-from .globals import request_ctx20 from .globals import session21 from .signals import message_flashed22 23 if t.TYPE_CHECKING: # pragma: no cover38 unmodified lines62 def stream_with_context(63 generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]],64 ) -> t.Iterator[t.AnyStr] | t.Callable[[t.Iterator[t.AnyStr]], t.Iterator[t.AnyStr]]:65 """Wrap a response generator function so that it runs inside the current67- request context. This keeps :data:`request`, :data:`session`, and :data:`g`66+ request context. This keeps :data:`.request`, :data:`.session`, and :data:`.g`67 available, even though at the point the generator runs the request context68 will typically have ended.69 70 Use it as a decorator on a generator function:39 unmodified lines110 111 return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]112 113 def generator() -> t.Iterator[t.AnyStr]:115- if (req_ctx := _cv_request.get(None)) is None:114+ if (ctx := _cv_app.get(None)) is None:115 raise RuntimeError(116 "'stream_with_context' can only be used when a request"117 " context is active, such as in a view function."118 )119 121- app_ctx = _cv_app.get()122- # Setup code below will run the generator to this point, so that the123- # current contexts are recorded. The contexts must be pushed after,124- # otherwise their ContextVar will record the wrong event loop during125- # async view functions.126- yield None # type: ignore[misc]120+ with ctx:121+ yield None # type: ignore[misc]122 128- # Push the app context first, so that the request context does not129- # automatically create and push a different app context.130- with app_ctx, req_ctx:123 try:124 yield from gen125 finally:126 # Clean up in case the user wrapped a WSGI iterator.127 if hasattr(gen, "close"):128 gen.close()129 138- # Execute the generator to the sentinel value. This ensures the context is139- # preserved in the generator's state. Further iteration will push the140- # context and yield from the original iterator.130+ # Execute the generator to the sentinel value. This captures the current131+ # context and pushes it to preserve it. Further iteration will yield from132+ # the original iterator.133 wrapped_g = generator()134 next(wrapped_g)135 return wrapped_g136 118 unmodified lines255 .. versionadded:: 2.2256 Calls ``current_app.redirect`` if available instead of always257 using Werkzeug's default ``redirect``.258 """267- if current_app:268- return current_app.redirect(location, code=code)259+ if (ctx := _cv_app.get(None)) is not None:260+ return ctx.app.redirect(location, code=code)261 262 return _wz_redirect(location, code=code, Response=Response)263 264 13 unmodified lines278 .. versionadded:: 2.2279 Calls ``current_app.aborter`` if available instead of always280 using Werkzeug's default ``abort``.281 """290- if current_app:291- current_app.aborter(code, *args, **kwargs)282+ if (ctx := _cv_app.get(None)) is not None:283+ ctx.app.aborter(code, *args, **kwargs)284 285 _wz_abort(code, *args, **kwargs)286 287 43 unmodified lines331 # implementations that use external storage for keeping their keys/values.332 flashes = session.get("_flashes", [])333 flashes.append((category, message))334 session["_flashes"] = flashes343- app = current_app._get_current_object() # type: ignore335+ app = current_app._get_current_object()336 message_flashed.send(337 app,338 _async_wrapper=app.ensure_sync,339 message=message,31 unmodified lines371 :param with_categories: set to ``True`` to also receive categories.372 :param category_filter: filter of categories to limit return values. Only373 categories in the list will be returned.374 """383- flashes = request_ctx.flashes375+ flashes = app_ctx._flashes376 if flashes is None:377 flashes = session.pop("_flashes") if "_flashes" in session else []386- request_ctx.flashes = flashes378+ app_ctx._flashes = flashes379 if category_filter:380 flashes = list(filter(lambda f: f[0] in category_filter, flashes))381 if not with_categories:382 return [x[1] for x in flashes]383 return flashes384 385 386 def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:387+ ctx = app_ctx._get_current_object()388+389 if kwargs.get("max_age") is None:396- kwargs["max_age"] = current_app.get_send_file_max_age390+ kwargs["max_age"] = ctx.app.get_send_file_max_age391 392 kwargs.update(399- environ=request.environ,400- use_x_sendfile=current_app.config["USE_X_SENDFILE"],401- response_class=current_app.response_class,402- _root_path=current_app.root_path,393+ environ=ctx.request.environ,394+ use_x_sendfile=ctx.app.config["USE_X_SENDFILE"],395+ response_class=ctx.app.response_class,396+ _root_path=ctx.app.root_path,397 )398 return kwargs399 400 235 unmodified linesmodified:src/flask/templating.py+14 added-20 removed
6 unmodified lines7 from jinja2 import Template8 from jinja2 import TemplateNotFound9 10 from .globals import _cv_app11-from .globals import _cv_request11 from .globals import current_app13-from .globals import request12 from .helpers import stream_with_context13 from .signals import before_render_template14 from .signals import template_rendered15 6 unmodified lines22 def _default_template_ctx_processor() -> dict[str, t.Any]:23 """Default template context processor. Injects `request`,24 `session` and `g`.25 """28- appctx = _cv_app.get(None)29- reqctx = _cv_request.get(None)26+ ctx = _cv_app.get(None)27 rv: dict[str, t.Any] = {}31- if appctx is not None:32- rv["g"] = appctx.g33- if reqctx is not None:34- rv["request"] = reqctx.request35- rv["session"] = reqctx.session28+29+ if ctx is not None:30+ rv["g"] = ctx.g31+32+ if ctx.has_request:33+ rv["request"] = ctx.request34+ rv["session"] = ctx.session35+36 return rv37 38 39 class Environment(BaseEnvironment):104 unmodified lines144 :param template_name_or_list: The name of the template to render. If145 a list is given, the first name to exist will be rendered.146 :param context: The variables to make available in the template.147 """148- app = current_app._get_current_object() # type: ignore[attr-defined]148+ app = current_app._get_current_object()149 template = app.jinja_env.get_or_select_template(template_name_or_list)150 return _render(app, template, context)151 152 3 unmodified lines156 157 :param source: The source code of the template to render.158 :param context: The variables to make available in the template.159 """160- app = current_app._get_current_object() # type: ignore[attr-defined]160+ app = current_app._get_current_object()161 template = app.jinja_env.from_string(source)162 return _render(app, template, context)163 164 10 unmodified lines175 template_rendered.send(176 app, _async_wrapper=app.ensure_sync, template=template, context=context177 )178 179- rv = generate()179+ return stream_with_context(generate())180 181- # If a request context is active, keep it while generating.182- if request:183- rv = stream_with_context(rv)181 185- return rv186-187-182 def stream_template(183 template_name_or_list: str | Template | list[str | Template],184 **context: t.Any,185 ) -> t.Iterator[str]:6 unmodified lines192 :param context: The variables to make available in the template.193 194 .. versionadded:: 2.2195 """202- app = current_app._get_current_object() # type: ignore[attr-defined]196+ app = current_app._get_current_object()197 template = app.jinja_env.get_or_select_template(template_name_or_list)198 return _stream(app, template, context)199 200 6 unmodified lines207 :param context: The variables to make available in the template.208 209 .. versionadded:: 2.2210 """217- app = current_app._get_current_object() # type: ignore[attr-defined]211+ app = current_app._get_current_object()212 template = app.jinja_env.from_string(source)213 return _stream(app, template, context)modified:src/flask/testing.py+4 added-4 removed
105 unmodified lines106 return _werkzeug_version107 108 109 class FlaskClient(Client):110- """Works like a regular Werkzeug test client but has knowledge about111- Flask's contexts to defer the cleanup of the request context until112- the end of a ``with`` block. For general information about how to113- use this class refer to :class:`werkzeug.test.Client`.110+ """Works like a regular Werkzeug test client, with additional behavior for111+ Flask. Can defer the cleanup of the request context until the end of a112+ ``with`` block. For general information about how to use this class refer to113+ :class:`werkzeug.test.Client`.114 115 .. versionchanged:: 0.12116 `app.test_client()` includes preset default environment, which can be117 set after instantiation of the `app.test_client()` object in181 unmodified linesmodified:tests/conftest.py+9 added-8 removed
3 unmodified lines4 import pytest5 from _pytest import monkeypatch6 7 from flask import Flask8-from flask.globals import request_ctx8+from flask.globals import app_ctx as _app_ctx9 10 11 @pytest.fixture(scope="session", autouse=True)12 def _standard_os_environ():69 unmodified lines82 83 84 @pytest.fixture(autouse=True)85 def leak_detector():86+ """Fails if any app contexts are still pushed when a test ends. Pops all87+ contexts so subsequent tests are not affected.88+ """89 yield87-88- # make sure we're not leaking a request context since we are89- # testing flask internally in debug mode in a few cases90 leaks = []91- while request_ctx:92- leaks.append(request_ctx._get_current_object())93- request_ctx.pop()91 95- assert leaks == []92+ while _app_ctx:93+ leaks.append(_app_ctx._get_current_object())94+ _app_ctx.pop()95 96+ assert not leaks97 98+99 @pytest.fixture100 def modules_tmp_path(tmp_path, monkeypatch):101 """A temporary directory added to sys.path."""102 rv = tmp_path / "modules_tmp"27 unmodified linesmodified:tests/test_appctx.py+6 added-5 removed
1 import pytest2 3 import flask4 from flask.globals import app_ctx5-from flask.globals import request_ctx5 6 7 def test_basic_url_generation(app):8 app.config["SERVER_NAME"] = "localhost"96 unmodified lines105 106 with app.app_context():107 client.get("/")108 109+ # teardown request context, and with block context110- assert cleanup_stuff == [None]110+ assert cleanup_stuff == [None, None]111 112 113 def test_app_tearing_down_with_unhandled_exception(app, client):114 app.config["PROPAGATE_EXCEPTIONS"] = True10 unmodified lines125 with pytest.raises(ValueError, match="dummy"):126 with app.app_context():127 client.get("/")128 129- assert len(cleanup_stuff) == 1129+ assert len(cleanup_stuff) == 2130 assert isinstance(cleanup_stuff[0], ValueError)131 assert str(cleanup_stuff[0]) == "dummy"132+ # exception propagated, seen by request context and with block context133+ assert cleanup_stuff[0] is cleanup_stuff[1]134 135 136 def test_app_ctx_globals_methods(app, app_ctx):137 # get41 unmodified lines179 180 @app.route("/")181 def index():182 with app_ctx:181- with request_ctx:182- pass183+ pass184 185 assert flask.request.environ["werkzeug.request"] is not None186 return ""187 23 unmodified linesmodified:tests/test_reqctx.py+3 added-3 removed
1 unmodified line2 3 import pytest4 5 import flask6-from flask.globals import request_ctx6+from flask.globals import app_ctx7 from flask.sessions import SecureCookieSessionInterface8 from flask.sessions import SessionInterface9 10 try:141 unmodified lines152 153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"156- reqctx = request_ctx.copy()156+ ctx = app_ctx.copy()157 158 def g():159 assert not flask.request160 assert not flask.current_app161- with reqctx:161+ with ctx:162 assert flask.request163 assert flask.current_app == app164 assert flask.request.path == "/"165 assert flask.request.args["foo"] == "bar"160 unmodified linesmodified:tests/test_session_interface.py+2 added-2 removed
1 import flask2-from flask.globals import request_ctx2+from flask.globals import app_ctx3 from flask.sessions import SessionInterface4 5 6 def test_open_session_with_endpoint():6 unmodified lines13 def save_session(self, app, session, response):14 pass15 16 def open_session(self, app, request):17- request_ctx.match_request()17+ app_ctx.match_request()18 assert request.endpoint is not None19 20 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()7 unmodified linesmodified:tests/test_testing.py+2 added-2 removed
4 unmodified lines5 6 import flask7 from flask import appcontext_popped8 from flask.cli import ScriptInfo9-from flask.globals import _cv_request9+from flask.globals import _cv_app10 from flask.json import jsonify11 from flask.testing import EnvironBuilder12 from flask.testing import FlaskCliRunner13 367 unmodified lines381 382 # close the response, releasing the context held by stream_with_context383 rv.close()384 # only req_ctx fixture should still be pushed385- assert _cv_request.get(None) is req_ctx385+ assert _cv_app.get(None) is req_ctxmodified:CHANGES.rst+4 added
3 unmodified lines4 Unreleased5 6 - Drop support for Python 3.9. :pr:`5730`7 - Remove previously deprecated code: ``__version__``. :pr:`5648`8+- ``RequestContext`` has merged with ``AppContext``. ``RequestContext`` is now9+ a deprecated alias. If an app context is already pushed, it is not reused10+ when dispatching a request. This greatly simplifies the internal code for tracking11+ the active context. :issue:`5639`12 - ``template_filter``, ``template_test``, and ``template_global`` decorators13 can be used without parentheses. :issue:`5729`14 15 1624 unmodified lines