Skip to content
Myr

merge app and request context

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

authored by David Lord · committed by David Lord · parent 3301232 · 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

36 files+771 added−999 removed

modified:docs/patterns/sqlalchemy.rst+2 added-3 removed
129 unmodified lines
130 bind=engine))131 def init_db():132 metadata.create_all(bind=engine)133134As in the declarative approach, you need to close the session after135each request or application context shutdown. Put this into your136application module::134As in the declarative approach, you need to close the session after each app135context. Put this into your application module::136137 from yourapplication.database import db_session138139 @app.teardown_appcontext
74 unmodified lines
modified:docs/patterns/sqlite3.rst+3 added-3 removed
1Using SQLite 3 with Flask2=========================34In Flask you can easily implement the opening of database connections on5demand and closing them when the context dies (usually at the end of the6request).4You can implement a few functions to work with a SQLite connection during a5request context. The connection is created the first time it's accessed,6reused on subsequent access, until it is closed when the request context ends.78Here is a simple example of how you can use SQLite 3 with Flask::910 import sqlite3
137 unmodified lines
modified:docs/patterns/streaming.rst+5 added-5 removed
47 unmodified lines
4849Streaming with Context50----------------------5152The :data:`~flask.request` will not be active while the generator is53running, because the view has already returned at that point. If you try54to access ``request``, you'll get a ``RuntimeError``.52The :data:`.request` proxy will not be active while the generator is53running, because the app has already returned control to the WSGI server at that54point. If you try to access ``request``, you'll get a ``RuntimeError``.5556If your generator function relies on data in ``request``, use the57:func:`~flask.stream_with_context` wrapper. This will keep the request58context active during the generator.57:func:`.stream_with_context` wrapper. This will keep the request context active58during the generator.5960.. code-block:: python6162 from flask import stream_with_context, request
23 unmodified lines
modified:docs/tutorial/blog.rst+1 added-1 removed
303 unmodified lines
304The pattern ``{{ request.form['title'] or post['title'] }}`` is used to305choose what data appears in the form. When the form hasn't been306submitted, the original ``post`` data appears, but if invalid form data307was 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 variable309that's automatically available in templates.310311312Delete
24 unmodified lines
modified:docs/tutorial/database.rst+3 added-3 removed
58 unmodified lines
5960 if db is not None:61 db.close()6263: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 is64used to store data that might be accessed by multiple functions during65the request. The connection is stored and reused instead of creating a66new connection if ``get_db`` is called a second time in the same67request.6869:data:`current_app` is another special object that points to the Flask69:data:`.current_app` is another special object that points to the Flask70application handling the request. Since you used an application factory,71there is no application object when writing the rest of your code.72``get_db`` will be called when the application has been created and is73handling a request, so :data:`current_app` can be used.73handling a request, so :data:`.current_app` can be used.7475:func:`sqlite3.connect` establishes a connection to the file pointed at76by the ``DATABASE`` configuration key. This file doesn't have to exist77yet, and won't until you initialize the database later.
142 unmodified lines
modified:docs/tutorial/templates.rst+1 added-1 removed
69 unmodified lines
70 {% endfor %}71 {% block content %}{% endblock %}72 </section>7374: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 username76and a log out link are displayed, or links to register and log in77are displayed. :func:`url_for` is also automatically available, and is78used to generate URLs to views instead of writing them out manually.
109 unmodified lines
modified:docs/tutorial/tests.rst+3 added-3 removed
309 unmodified lines
310input and error messages without writing the same code three times.311312The 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.315316.. code-block:: python317 :caption: ``tests/test_auth.py``318
16 unmodified lines
335 response = auth.login(username, password)336 assert message in response.data337338Using ``client`` in a ``with`` block allows accessing context variables339such as :data:`session` after the response is returned. Normally,339such as :data:`.session` after the response is returned. Normally,340accessing ``session`` outside of a request would raise an error.341342Testing ``logout`` is the opposite of ``login``. :data:`session` should342Testing ``logout`` is the opposite of ``login``. :data:`.session` should343not contain ``user_id`` after logging out.344345.. code-block:: python346 :caption: ``tests/test_auth.py``
213 unmodified lines
modified:docs/tutorial/views.rst+4 added-4 removed
206 unmodified lines
207#. :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.210211#. :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.216217Now that the user's ``id`` is stored in the :data:`session`, it will be217Now that the user's ``id`` is stored in the :data:`.session`, it will be218available on subsequent requests. At the beginning of each request, if219a user is logged in their information should be loaded and made220available to other views.221
13 unmodified lines
235236:meth:`bp.before_app_request() <Blueprint.before_app_request>` registers237a function that runs before the view function, no matter what URL is238requested. ``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 it240on :data:`g.user <g>`, which lasts for the length of the request. If241there is no user id, or if the id doesn't exist, ``g.user`` will be242``None``.243244245Logout246------247248To log out, you need to remove the user id from the :data:`session`.248To log out, you need to remove the user id from the :data:`.session`.249Then ``load_logged_in_user`` won't load a user on subsequent requests.250251.. code-block:: python252 :caption: ``flaskr/auth.py``
53 unmodified lines
modified:docs/api.rst+58 added-67 removed
29 unmodified lines
30 :members:31 :inherited-members:32 :exclude-members: json_module3334.. attribute:: request34.. data:: request3536 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`.3842 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.4144 The request object is an instance of a :class:`~flask.Request`.42 This is a proxy. See :ref:`context-visibility` for more information.434445Response Objects46----------------
12 unmodified lines
59does this is by using a signed cookie. The user can look at the session60contents, but can't modify it unless they know the secret key, so make sure to61set that to something complex and unguessable.6265To access the current session you can use the :class:`session` object:63To access the current session you can use the :data:`.session` proxy.6467.. class:: session65.. data:: session6669 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`.6972 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.7274 The following attributes are interesting:73 This is a proxy. See :ref:`context-visibility` for more information.7476 .. 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.7878 ``True`` if the session is new, ``False`` otherwise.79 .. code-block:: python8080 .. attribute:: modified8182 ``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::8687 # 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 = True8593 .. 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`.9095 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.9110092Session Interface93-----------------9495.. versionadded:: 0.8
52 unmodified lines
148another, a global variable is not good enough because it would break in149threaded environments. Flask provides you with a special object that150ensures it is only valid for the active request and that will return151different values for each request. In a nutshell: it does the right161thing, like it does for :class:`request` and :class:`session`.152thing, like it does for :data:`.request` and :data:`.session`.153154.. data:: g155165 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`.159170 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.163174 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.165166 This is a proxy. See :ref:`context-visibility` for more information.167168 .. versionchanged:: 0.10169 Bound to the application context instead of the request context.170171.. autoclass:: flask.ctx._AppCtxGlobals
4 unmodified lines
176----------------------------177178.. data:: current_app179188 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.182193 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.186198 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.188189 This is a proxy. See :ref:`context-visibility` for more information.190191.. autofunction:: has_request_context192193.. autofunction:: copy_current_request_context194
94 unmodified lines
289290Useful Internals291----------------292302.. autoclass:: flask.ctx.RequestContext293.. autoclass:: flask.ctx.AppContext294 :members:295305.. data:: flask.globals.request_ctx296.. data:: flask.globals.app_ctx297307 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`.299311 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.303315.. autoclass:: flask.ctx.AppContext316 :members:304 This is only available when a :doc:`request context </appcontext>` is305 active.306318.. data:: flask.globals.app_ctx307 This is a proxy. See :ref:`context-visibility` for more information.308320 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.RequestContext310324 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.313314.. data:: flask.globals.request_ctx315316 .. deprecated:: 3.2317 Merged with :data:`.app_ctx`. This alias will be removed in Flask 4.0.318319.. autoclass:: flask.blueprints.BlueprintSetupState320 :members:321322.. _core-signals-list:
386 unmodified lines
modified:docs/appcontext.rst+137 added-98 removed
1.. currentmodule:: flask1The App and Request Context2===========================33The Application Context4=======================4The context keeps track of data and objects during a request, CLI command, or5other activity. Rather than passing this data around to every function, the6:data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session` proxies7are accessed instead.86The application context keeps track of the application-level data during7a request, CLI command, or other activity. Rather than passing the8application around to each function, the :data:`current_app` and9:data:`g` proxies are accessed instead.9When handling a request, the context is referred to as the "request context"10because it contains request data in addition to application data. Otherwise,11such as during a CLI command, it is referred to as the "app context". During an12app context, :data:`.current_app` and :data:`.g` are available, while during a13request context :data:`.request` and :data:`.session` are also available.1411This is similar to :doc:`/reqcontext`, which keeps track of12request-level data during a request. A corresponding application context13is pushed when a request context is pushed.1516Purpose of the Context17----------------------1818The :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`` instance21within the modules in your project is prone to circular import issues.22When using the :doc:`app factory pattern </patterns/appfactories>` or23writing reusable :doc:`blueprints </blueprints>` or24:doc:`extensions </extensions>` there won't be an ``app`` instance to25import at all.19The context and proxies help solve two development issues: circular imports, and20passing around global data during a request.2127Flask solves this issue with the *application context*. Rather than28referring to an ``app`` directly, you use the :data:`current_app`29proxy, which points to the application handling the current activity.22The :class:`.Flask` application object has attributes, such as23:attr:`~.Flask.config`, that are useful to access within views and other24functions. However, importing the ``app`` instance within the modules in your25project 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't28be an ``app`` instance to import at all.2931Flask automatically *pushes* an application context when handling a32request. View functions, error handlers, and other functions that run33during a request will have access to :data:`current_app`.30When the application handles a request, it creates a :class:`.Request` object.31Because a *worker* handles only one request at a time, the request data can be32considered global to that worker during that request. Passing it as an argument33through every function during the request becomes verbose and redundant.3435Flask will also automatically push an app context when running CLI36commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.35Flask solves these issues with the *active context* pattern. Rather than36importing an ``app`` directly, or having to pass it and the request through to37every single function, you import and access the proxies, which point to the38currently active application and request data. This is sometimes referred to39as "context local" data.404139Lifetime of the Context40-----------------------42Context During Setup43--------------------4442The application context is created and destroyed as necessary. When a43Flask application begins handling a request, it pushes an application44context and a :doc:`request context </reqcontext>`. When the request45ends it pops the request context then the application context.46Typically, an application context will have the same lifetime as a47request.45If you try to access :data:`.current_app`, :data:`.g`, or anything that uses it,46outside an app context, you'll get this error message:4749See :doc:`/reqcontext` for more information about how the contexts work50and the full life cycle of a request.515253Manually Push a Context54-----------------------5556If you try to access :data:`current_app`, or anything that uses it,57outside an application context, you'll get this error message:5848.. code-block:: pytb4950 RuntimeError: Working outside of application context.5163 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.5556If you see that error while configuring your application, such as when68initializing an extension, you can push a context manually since you69have direct access to the ``app``. Use :meth:`~Flask.app_context` in a70``with`` block, and everything that runs in the block will have access71to :data:`current_app`. ::57initializing an extension, you can push a context manually since you have direct58access to the ``app``. Use :meth:`.Flask.app_context` in a ``with`` block.5960.. code-block:: python6162 def create_app():63 app = Flask(__name__)6465 with app.app_context():66 init_db()6768 return app6981If you see that error somewhere else in your code not related to82configuring the application, it most likely indicates that you should83move that code into a view function or CLI command.70If you see that error somewhere else in your code not related to setting up the71application, it most likely indicates that you should move that code into a view72function or CLI command.737486Storing Data87------------75Context During Testing76----------------------7789The application context is a good place to store common data during a90request or CLI command. Flask provides the :data:`g object <g>` for this91purpose. It is a simple namespace object that has the same lifetime as92an application context.78See :doc:`/testing` for detailed information about managing the context during79tests.8094.. 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.81If you try to access :data:`.request`, :data:`.session`, or anything that uses82it, outside a request context, you'll get this error message:83101A common use for :data:`g` is to manage resources during a request.84.. code-block:: pytb851031. ``get_X()`` creates resource ``X`` if it does not exist, caching it104 as ``g.X``.1052. ``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.87109For 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.90111 from flask import g91This will probably only happen during tests. If you see that error somewhere92else in your code not related to testing, it most likely indicates that you93should move that code into a view function.94113 def get_db():114 if 'db' not in g:115 g.db = connect_to_database()95The primary way to solve this is to use :meth:`.Flask.test_client` to simulate96a full request.97117 return g.db98If you only want to unit test one function, rather than a full request, use99:meth:`.Flask.test_request_context` in a ``with`` block.100119 @app.teardown_appcontext120 def teardown_db(exception):121 db = g.pop('db', None)101.. code-block:: python102123 if db is not None:124 db.close()103 def generate_report(year):104 format = request.args.get("format")105 ...106126During a request, every call to ``get_db()`` will return the same127connection, and it will be closed automatically at the end of the128request.107 with app.test_request_context(108 "/make_report/2017", query_string={"format": "short"}109 ):110 generate_report()111130You can use :class:`~werkzeug.local.LocalProxy` to make a new context131local from ``get_db()``::112133 from werkzeug.local import LocalProxy134 db = LocalProxy(get_db)113.. _context-visibility:114136Accessing ``db`` will call ``get_db`` internally, in the same way that137:data:`current_app` works.115Visibility of the Context116-------------------------117118The context will have the same lifetime as an activity, such as a request, CLI119command, or ``with`` block. Various callbacks and signals registered with the120app will be run during the context.121140Events and Signals141------------------122When a Flask application handles a request, it pushes a requet context123to set the active application and request data. When it handles a CLI command,124it pushes an app context to set the active application. When the activity ends,125it pops that context. Proxy objects like :data:`.request`, :data:`.session`,126:data:`.g`, and :data:`.current_app`, are accessible while the context is pushed127and active, and are not accessible after the context is popped.128143The application will call functions registered with :meth:`~Flask.teardown_appcontext`144when the application context is popped.129The context is unique to each thread (or other worker type). The proxies cannot130be passed to another worker, which has a different context space and will not131know about the active context in the parent's space.132146The following signals are sent: :data:`appcontext_pushed`,147:data:`appcontext_tearing_down`, and :data:`appcontext_popped`.133Besides being scoped to each worker, the proxy object has a separate type and134identity than the proxied real object. In some cases you'll need access to the135real object, rather than the proxy. Use the136:meth:`~.LocalProxy._get_current_object` method in those cases.137138.. code-block:: python139140 app = current_app._get_current_object()141 my_signal.send(app)142143144Lifcycle of the Context145-----------------------146147Flask dispatches a request in multiple stages which can affect the request,148response, and how errors are handled. See :doc:`/lifecycle` for a list of all149the steps, callbacks, and signals during each request. The following are the150steps directly related to the context.151152- 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.161162The teardown callbacks are called by the context when it is popped. They are163called even if there is an unhandled exception during dispatch. They may be164called multiple times in some test scenarios. This means there is no guarantee165that any other parts of the request dispatch have run. Be sure to write these166functions in a way that does not depend on other callbacks and will not fail.167168169How the Context Works170---------------------171172Context locals are implemented using Python's :mod:`contextvars` and Werkzeug's173:class:`~werkzeug.local.LocalProxy`. Python's contextvars are a low level174structure to manage data local to a thread or coroutine. ``LocalProxy`` wraps175the contextvar so that access to any attributes and methods is forwarded to the176object stored in the contextvar.177178The context is tracked like a stack, with the active context at the top of the179stack. Flask manages pushing and popping contexts during requests, CLI commands,180testing, ``with`` blocks, etc. The proxies access attributes on the active181context.182183Because it is a stack, other contexts may be pushed to change the proxies during184an already active context. This is not a common pattern, but can be used in185advanced use cases. For example, a Flask application can be used as WSGI186middleware, calling another wrapped Flask app from a view.
modified:docs/design.rst+12 added-11 removed
167 unmodified lines
168infrastructure, packages with dependencies are no longer an issue and169there are very few reasons against having libraries that depend on others.170171172Thread Locals173-------------172Context Locals173--------------174175Flask uses thread local objects (context local objects in fact, they176support greenlet contexts as well) for request, session and an extra177object you can put your own things on (:data:`~flask.g`). Why is that and178isn't that a bad idea?175Flask uses special context locals and proxies to provide access to the176current app and request data to any code running during a request, CLI command,177etc. Context locals are specific to the worker handling the activity, such as a178thread, process, coroutine, or greenlet.179180Yes it is usually not such a bright idea to use thread locals. They cause181troubles for servers that are not based on the concept of threads and make182large applications harder to maintain. However Flask is just not designed183for large applications or asynchronous servers. Flask wants to make it184quick and easy to write a traditional web application.180The context and proxies help solve two development issues: circular imports, and181passing around global data. :data:`.current_app: can be used to access the182application object without needing to import the app object directly, avoiding183circular import issues. :data:`.request`, :data:`.session`, and :data`.g` can be184imported to access the current data for the request, rather than needing to185pass them as arguments through every single function in your project.186187188Async/await and ASGI support189----------------------------
40 unmodified lines
modified:docs/extensiondev.rst+8 added-9 removed
65 unmodified lines
6667It is important that the app is not stored on the extension, don't do68``self.app = app``. The only time the extension should have direct69access to an app is during ``init_app``, otherwise it should use70:data:`current_app`.70:data:`.current_app`.7172This allows the extension to support the application factory pattern,73avoids circular import issues when importing the extension instance74elsewhere in a user's code, and makes testing with different
29 unmodified lines
104105A common pattern is to use :meth:`~Flask.before_request` to initialize106some data or a connection at the beginning of each request, then107:meth:`~Flask.teardown_request` to clean it up at the end. This can be108stored on :data:`g`, discussed more below.108stored on :data:`.g`, discussed more below.109110A more lazy approach is to provide a method that initializes and caches111the data or connection. For example, a ``ext.get_db`` method could112create a database connection the first time it's called, so that a view
65 unmodified lines
178 from types import SimpleNamespace179 g._hello = SimpleNamespace()180 g._hello.user_id = 2181182The data in ``g`` lasts for an application context. An application183context is active when a request context is, or when a CLI command is184run. If you're storing something that should be closed, use185:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed186when the application context ends. If it should only be valid during a187request, or would not be used in the CLI outside a request, use188:meth:`~flask.Flask.teardown_request`.182The data in ``g`` lasts for an application context. An application context is183active during a request, CLI command, or ``with app.app_context()`` block. If184you're storing something that should be closed, use185:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed when the186app context ends. If it should only be valid during a request, or would not be187used in the CLI outside a request, use :meth:`~flask.Flask.teardown_request`.188189190Views and Models191----------------
114 unmodified lines
modified:docs/index.rst-1 removed
50 unmodified lines
51 signals52 views53 lifecycle54 appcontext55 reqcontext55 blueprints56 extensions57 cli58 server
30 unmodified lines
modified:docs/lifecycle.rst+16 added-13 removed
115 unmodified lines
116the view function, and pass the return value back to the server. But there are many more117parts that you can use to customize its behavior.118119#. 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 lines
137 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 lines
151 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.160161When executing a CLI command or plain app context without request data, the same162order of steps is followed, omitting the steps that refer to the request.163164A :class:`Blueprint` can add handlers for these events that are specific to the165blueprint. The handlers for a blueprint will run if the blueprint166owns the route that matches the request.167168There are even more decorators and customization points than this, but that aren't part169of every request lifecycle. They're more specific to certain things you might use during170a request, such as templates, building URLs, or handling JSON data. See the rest of this171documentation, as well as the :doc:`api` to explore further.
modified:docs/quickstart.rst+38 added-85 removed
256 unmodified lines
257258For example, here we use the :meth:`~flask.Flask.test_request_context` method259to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`260tells Flask to behave as though it's handling a request even while we use a261Python shell. See :ref:`context-locals`.261Python shell. See :doc:`/appcontext`.262263.. code-block:: python264265 from flask import url_for
182 unmodified lines
448449Accessing Request Data450----------------------451452For web applications it's crucial to react to the data a client sends to453the server. In Flask this information is provided by the global454:class:`~flask.request` object. If you have some experience with Python455you might be wondering how that object can be global and how Flask456manages to still be threadsafe. The answer is context locals:452For web applications it's crucial to react to the data a client sends to the453server. In Flask this information is provided by the global :data:`.request`454object, which is an instance of :class:`.Request`. This object has many455attributes and methods to work with the incoming request data, but here is a456broad overview. First it needs to be imported.457458.. code-block:: python459459.. _context-locals:460461Context Locals462``````````````463464.. admonition:: Insider Information465466 If you want to understand how that works and how you can implement467 tests with context locals, read this section, otherwise just skip it.468469Certain objects in Flask are global objects, but not of the usual kind.470These objects are actually proxies to objects that are local to a specific471context. What a mouthful. But that is actually quite easy to understand.472473Imagine the context being the handling thread. A request comes in and the474web server decides to spawn a new thread (or something else, the475underlying object is capable of dealing with concurrency systems other476than threads). When Flask starts its internal request handling it477figures out that the current thread is the active context and binds the478current application and the WSGI environments to that context (thread).479It does that in an intelligent way so that one application can invoke another480application without breaking.481482So what does this mean to you? Basically you can completely ignore that483this is the case unless you are doing something like unit testing. You484will notice that code which depends on a request object will suddenly break485because there is no request object. The solution is creating a request486object yourself and binding it to the context. The easiest solution for487unit testing is to use the :meth:`~flask.Flask.test_request_context`488context manager. In combination with the ``with`` statement it will bind a489test request so that you can interact with it. Here is an example::490460 from flask import request461493 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'462If you have some experience with Python you might be wondering how that object463can be global when Flask handles multiple requests at a time. The answer is464that :data:`.request` is actually a proxy, pointing at whatever request is465currently being handled by a given worker, which is managed interanlly by Flask466and Python. See :doc:`/appcontext` for much more information.467499The other possibility is passing a whole WSGI environment to the500:meth:`~flask.Flask.request_context` method::468The current request method is available in the :attr:`~.Request.method`469attribute. To access form data (data transmitted in a ``POST`` or ``PUT``470request), use the :attr:`~flask.Request.form` attribute, which behaves like a471dict.472502 with app.request_context(environ):503 assert request.method == 'POST'473.. code-block:: python474505The Request Object506``````````````````507508The request object is documented in the API section and we will not cover509it here in detail (see :class:`~flask.Request`). Here is a broad overview of510some of the most common operations. First of all you have to import it from511the ``flask`` module::512513 from flask import request514515The current request method is available by using the516:attr:`~flask.Request.method` attribute. To access form data (data517transmitted in a ``POST`` or ``PUT`` request) you can use the518:attr:`~flask.Request.form` attribute. Here is a full example of the two519attributes mentioned above::520521 @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'])478479 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"484534What happens if the key does not exist in the ``form`` attribute? In that535case a special :exc:`KeyError` is raised. You can catch it like a536standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request537error page is shown instead. So for many situations you don't have to538deal with that problem.485 # Executed if the request method was GET or the credentials were invalid.486 return render_template("login.html", error=error)487540To access parameters submitted in the URL (``?key=value``) you can use the541:attr:`~flask.Request.args` attribute::488If the key does not exist in ``form``, a special :exc:`KeyError` is raised. You489can catch it like a normal ``KeyError``, otherwise it will return a HTTP 400490Bad Request error page. You can also use the491:meth:`~werkzeug.datastructures.MultiDict.get` method to get a default492instead of an error.493543 searchword = request.args.get('key', '')494To access parameters submitted in the URL (``?key=value``), use the495:attr:`~.Request.args` attribute. Key errors behave the same as ``form``,496returning a 400 response if not caught.497545We recommend accessing URL parameters with `get` or by catching the546:exc:`KeyError` because users might change the URL and presenting them a 400547bad request page in that case is not user friendly.498.. code-block:: python499549For a full list of methods and attributes of the request object, head over550to the :class:`~flask.Request` documentation.500 searchword = request.args.get('key', '')501502For a full list of methods and attributes of the request object, see the503:class:`~.Request` documentation.504505506File Uploads507````````````508509You can handle uploaded files with Flask easily. Just make sure not to
349 unmodified lines
modified:docs/reqcontext.rst+2 added-239 removed
1.. currentmodule:: flask1:orphan:23The Request Context4===================56The request context keeps track of the request-level data during a7request. Rather than passing the request object to each function that8runs during a request, the :data:`request` and :data:`session` proxies9are accessed instead.1011This is similar to :doc:`/appcontext`, which keeps track of the12application-level data independent of a request. A corresponding13application context is pushed when a request context is pushed.141516Purpose of the Context17----------------------1819When the :class:`Flask` application handles a request, it creates a20:class:`Request` object based on the environment it received from the21WSGI server. Because a *worker* (thread, process, or coroutine depending22on the server) handles only one request at a time, the request data can23be considered global to that worker during that request. Flask uses the24term *context local* for this.2526Flask automatically *pushes* a request context when handling a request.27View functions, error handlers, and other functions that run during a28request will have access to the :data:`request` proxy, which points to29the request object for the current request.303132Lifetime of the Context33-----------------------3435When a Flask application begins handling a request, it pushes a request36context, which also pushes an :doc:`app context </appcontext>`. When the37request ends it pops the request context then the application context.3839The context is unique to each thread (or other worker type).40:data:`request` cannot be passed to another thread, the other thread has41a different context space and will not know about the request the parent42thread was pointing to.4344Context locals are implemented using Python's :mod:`contextvars` and45Werkzeug's :class:`~werkzeug.local.LocalProxy`. Python manages the46lifetime of context vars automatically, and local proxy wraps that47low-level interface to make the data easier to work with.484950Manually Push a Context51-----------------------5253If you try to access :data:`request`, or anything that uses it, outside54a request context, you'll get this error message:5556.. code-block:: pytb5758 RuntimeError: Working outside of request context.5960 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.6364This should typically only happen when testing code that expects an65active request. One option is to use the66:meth:`test client <Flask.test_client>` to simulate a full request. Or67you can use :meth:`~Flask.test_request_context` in a ``with`` block, and68everything that runs in the block will have access to :data:`request`,69populated with your test data. ::7071 def generate_report(year):72 format = request.args.get("format")73 ...7475 with app.test_request_context(76 "/make_report/2017", query_string={"format": "short"}77 ):78 generate_report()7980If you see that error somewhere else in your code not related to81testing, it most likely indicates that you should move that code into a82view function.8384For information on how to use the request context from the interactive85Python shell, see :doc:`/shell`.868788How the Context Works89---------------------9091The :meth:`Flask.wsgi_app` method is called to handle each request. It92manages the contexts during the request. Internally, the request and93application contexts work like stacks. When contexts are pushed, the94proxies that depend on them are available and point at information from95the top item.9697When the request starts, a :class:`~ctx.RequestContext` is created and98pushed, which creates and pushes an :class:`~ctx.AppContext` first if99a context for that application is not already the top context. While100these contexts are pushed, the :data:`current_app`, :data:`g`,101:data:`request`, and :data:`session` proxies are available to the102original thread handling the request.103104Other contexts may be pushed to change the proxies during a request.105While this is not a common pattern, it can be used in advanced106applications to, for example, do internal redirects or chain different107applications together.108109After the request is dispatched and a response is generated and sent,110the request context is popped, which then pops the application context.111Immediately before they are popped, the :meth:`~Flask.teardown_request`112and :meth:`~Flask.teardown_appcontext` functions are executed. These113execute even if an unhandled exception occurred during dispatch.114115116.. _callbacks-and-errors:117118Callbacks and Errors119--------------------120121Flask dispatches a request in multiple stages which can affect the122request, response, and how errors are handled. The contexts are active123during all of these stages.124125A :class:`Blueprint` can add handlers for these events that are specific126to the blueprint. The handlers for a blueprint will run if the blueprint127owns the route that matches the request.128129#. 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.133134#. 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.137138#. 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.141142#. 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.146147If an exception is raised before the teardown functions, Flask tries to148match it with an :meth:`~Flask.errorhandler` function to handle the149exception and return a response. If no error handler is found, or the150handler itself raises an exception, Flask returns a generic151``500 Internal Server Error`` response. The teardown functions are still152called, and are passed the exception object.153154If debug mode is enabled, unhandled exceptions are not converted to a155``500`` response and instead are propagated to the WSGI server. This156allows the development server to present the interactive debugger with157the traceback.158159160Teardown Callbacks161~~~~~~~~~~~~~~~~~~162163The teardown callbacks are independent of the request dispatch, and are164instead called by the contexts when they are popped. The functions are165called even if there is an unhandled exception during dispatch, and for166manually pushed contexts. This means there is no guarantee that any167other parts of the request dispatch have run first. Be sure to write168these functions in a way that does not depend on other callbacks and169will not fail.170171During testing, it can be useful to defer popping the contexts after the172request ends, so that their data can be accessed in the test function.173Use the :meth:`~Flask.test_client` as a ``with`` block to preserve the174contexts until the ``with`` block exits.175176.. code-block:: python177178 from flask import Flask, request179180 app = Flask(__name__)181182 @app.route('/')183 def hello():184 print('during view')185 return 'Hello, World!'186187 @app.teardown_request188 def show_teardown(exception):189 print('after with block')190191 with app.test_request_context():192 print('during with block')193194 # teardown functions are called after the context with block exits195196 with app.test_client() as client:197 client.get('/')198 # the contexts are not popped even though the request ended199 print(request.path)200201 # the contexts are popped and teardown functions are called after202 # the client with block exits203204Signals205~~~~~~~206207The following signals are sent:208209#. :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.217218219.. _notes-on-proxies:220221Notes On Proxies222----------------223224Some of the objects provided by Flask are proxies to other objects. The225proxies are accessed in the same way for each worker thread, but226point to the unique object bound to each worker behind the scenes as227described on this page.228229Most of the time you don't have to care about that, but there are some230exceptions where it is good to know that this object is actually a proxy:231232- 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.238239If you need to access the underlying object that is proxied, use the240:meth:`~werkzeug.local.LocalProxy._get_current_object` method::241242 app = current_app._get_current_object()243 my_signal.send(app)6Obsolete, see :doc:`/appcontext` instead.
modified:docs/shell.rst+16 added-35 removed
1Working with the Shell2======================34.. versionadded:: 0.34One of the reasons everybody loves Python is the interactive shell. It allows5you to play around with code in real time and immediately get results back.6Flask provides the ``flask shell`` CLI command to start an interactive Python7shell with some setup done to make working with the Flask app easier.86One of the reasons everybody loves Python is the interactive shell. It7basically allows you to execute Python commands in real time and8immediately get results back. Flask itself does not come with an9interactive shell, because it does not require any specific setup upfront,10just import your application and start playing around.9.. code-block:: text1012There are however some handy helpers to make playing around in the shell a13more pleasant experience. The main issue with interactive console14sessions is that you're not triggering a request like a browser does which15means that :data:`~flask.g`, :data:`~flask.request` and others are not16available. But the code you want to test might depend on them, so what17can you do?11 $ flask shell1219This is where some helper functions come in handy. Keep in mind however20that these functions are not only there for interactive shell usage, but21also for unit testing and other situations that require a faked request22context.2324Generally it's recommended that you read :doc:`reqcontext` first.2526Command Line Interface27----------------------2829Starting 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.31For instance the shell is automatically initialized with a loaded32application context.3334For more information see :doc:`/cli`.3513Creating a Request Context14--------------------------1516``flask shell`` pushes an app context automatically, so :data:`.current_app` and17:data:`.g` are already available. However, there is no HTTP request being18handled in the shell, so :data:`.request` and :data:`.session` are not yet19available.2021The easiest way to create a proper request context from the shell is by22using the :attr:`~flask.Flask.test_request_context` method which creates23us a :class:`~flask.ctx.RequestContext`:2425>>> ctx = app.test_request_context()2645Normally you would use the ``with`` statement to make this request object46active, but in the shell it's easier to use the47:meth:`~flask.ctx.RequestContext.push` and48:meth:`~flask.ctx.RequestContext.pop` methods by hand:27Normally you would use the ``with`` statement to make this context active, but28in the shell it's easier to call :meth:`~.RequestContext.push` and29:meth:`~.RequestContext.pop` manually:3031>>> ctx.push()3252From that point onwards you can work with the request object until you53call `pop`:33From that point onwards you can work with the request object until you call34``pop``:3536>>> ctx.pop()3738Firing Before/After Request
43 unmodified lines
modified:docs/signals.rst+4 added-5 removed
142 unmodified lines
143144Signals and Flask's Request Context145-----------------------------------146147Signals fully support :doc:`reqcontext` when receiving signals.148Context-local variables are consistently available between149:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can150rely on :class:`flask.g` and others as needed. Note the limitations described151in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.147Context-local proxies are available between :data:`~flask.request_started` and148:data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others149as needed. Note the limitations described in :ref:`signals-sending` and the150:data:`~flask.request_tearing_down` signal.151152153Decorator Based Signal Subscriptions154------------------------------------
12 unmodified lines
modified:docs/testing.rst+4 added-5 removed
273 unmodified lines
274275Tests that depend on an Active Context276--------------------------------------277278You may have functions that are called from views or commands, that279expect 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 a282request or invoking the command, you can create and activate a context278You may have functions that are called from views or commands, that expect an279active :doc:`app context </appcontext>` because they access :data:`.request`,280:data:`.session`, :data:`.g`, or :data:`.current_app`. Rather than testing them by281making a request or invoking the command, you can create and activate a context282directly.283284Use ``with app.app_context()`` to push an application context. For285example, database extensions usually require an active app context to
33 unmodified lines
modified:src/flask/json/__init__.py+1 added-1 removed
139 unmodified lines
140 :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.143144 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>`.146147 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 lines
modified:src/flask/sansio/app.py+5 added-11 removed
175 unmodified lines
176 #: 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 = _AppCtxGlobals183184 #: The class that is used for the ``config`` attribute of this app.185 #: Defaults to :class:`~flask.Config`.
635 unmodified lines
821 self.jinja_env.globals[name or f.__name__] = f822823 @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.828829 .. code-block:: python830831 with app.app_context():832 ...833834 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.837838 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 exception
166 unmodified lines
modified:src/flask/sansio/scaffold.py+2 added-2 removed
505 unmodified lines
506507 @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.512513 .. code-block:: python514515 with app.test_request_context():
277 unmodified lines
modified:src/flask/app.py+70 added-106 removed
27 unmodified lines
2829from . import cli30from . import typing as ft31from .ctx import AppContext32from .ctx import RequestContext32from .globals import _cv_app34from .globals import _cv_request35from .globals import current_app33from .globals import g34from .globals import request38from .globals import request_ctx35from .globals import session36from .helpers import get_debug_flag37from .helpers import get_flashed_messages38from .helpers import get_load_dotenv39from .helpers import send_from_directory40from .sansio.app import App45from .sansio.scaffold import _sentinel41from .sessions import SecureCookieSessionInterface42from .sessions import SessionInterface43from .signals import appcontext_tearing_down44from .signals import got_request_exception
244 unmodified lines
289 The default configuration is ``None`` instead of 12 hours.290291 .. versionadded:: 0.9292 """298 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]293 value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]294295 if value is None:296 return None297
213 unmodified lines
511 """512 names: t.Iterable[str | None] = (None,)513514 # 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))517518 # 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 lines
880 .. 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().request885886 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 the
62 unmodified lines
952 behavior of ``OPTIONS`` responses.953954 .. 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 rv
91 unmodified lines
10521053 .. 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.blueprint10591062 if req_ctx is not None:1063 url_adapter = req_ctx.url_adapter1064 blueprint_name = req_ctx.request.blueprint10651060 # 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 lines
1069 # 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)10801073 # 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)10801081 if url_adapter is None:
187 unmodified lines
1269 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))12751276 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)12801281 for name in names:1282 if name in self.before_request_funcs:1283 for before_func in self.before_request_funcs[name]:
16 unmodified lines
1300 :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()13051306 for func in ctx._after_request_functions:1307 response = self.ensure_sync(func)(response)13081316 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 line
1315 self.session_interface.save_session(self, ctx.session, response)13161317 return response13181326 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`.13231333 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.13271338 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.13301343 :param exc: An unhandled exception raised while dispatching the1344 request. Detected from the current exception information if1345 not passed. Passed to each teardown function.13461331 .. versionchanged:: 0.91332 Added the ``exc`` argument.1333 """1350 if exc is _sentinel:1351 exc = sys.exc_info()[1]1334 req = _cv_app.get().request13351353 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)13401341 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)13421360 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`.13461366 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.13491369 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.13521373 This is called by1374 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.13751353 .. versionadded:: 0.91354 """1378 if exc is _sentinel:1379 exc = sys.exc_info()[1]13801355 for func in reversed(self.teardown_appcontext_funcs):1356 self.ensure_sync(func)(exc)13571358 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)13591360 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.13631391 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.13681396 ::1369 .. code-block:: python13701371 with app.app_context():1372 init_db()1373
2 unmodified lines
1376 .. versionadded:: 0.91377 """1378 return AppContext(self)13791407 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.13851412 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.13891414 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`.13911419 :param environ: a WSGI environment1392 :param environ: A WSGI environment.1393 """1421 return RequestContext(self, environ)1394 return AppContext.from_environ(self, environ)13951423 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.14001429 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.14041431 Use a ``with`` block to push the context, which will make1432 :data:`request` point at the request for the created1433 environment. ::1405 .. code-block:: python14061407 with app.test_request_context(...):1408 generate_report()14091438 When using the shell, it may be easier to push and pop the1439 context manually to avoid indentation. ::1410 See :doc:`/appcontext`.14111441 ctx = app.test_request_context(...)1442 ctx.push()1443 ...1444 ctx.pop()14451412 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.14161417 :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 EnvironBuilder14351436 builder = EnvironBuilder(self, *args, **kwargs)14371438 try:1475 return self.request_context(builder.get_environ())1439 environ = builder.get_environ()1440 finally:1441 builder.close()14421443 return self.request_context(environ)14441445 def wsgi_app(1446 self, environ: WSGIEnvironment, start_response: StartResponse1447 ) -> cabc.Iterable[bytes]:1448 """The actual WSGI application. This is not implemented in
12 unmodified lines
1461 .. 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`.14651466 :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 to
14 unmodified lines
1483 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())14871488 if error is not None and self.should_ignore_error(error):1489 error = None1490
10 unmodified lines
modified:src/flask/cli.py+1 added-1 removed
626 unmodified lines
627628 # 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())633634 return app.cli.get_command(ctx, name)635
492 unmodified lines
modified:src/flask/ctx.py+261 added-194 removed
1from __future__ import annotations23import contextvars4import sys4import typing as t5from functools import update_wrapper6from types import TracebackType78from werkzeug.exceptions import HTTPException9from werkzeug.routing import MapAdapter1011from . import typing as ft12from .globals import _cv_app13from .globals import _cv_request13from .signals import appcontext_popped14from .signals import appcontext_pushed1517if t.TYPE_CHECKING: # pragma: no cover16if t.TYPE_CHECKING:17 import typing_extensions as te18 from _typeshed.wsgi import WSGIEnvironment1920 from .app import Flask21 from .sessions import SessionMixin
8 unmodified lines
30 """A plain object. Used as a namespace for storing data during an31 application context.3233 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.3536 .. describe:: 'key' in g3738 Check whether an attribute is present.
77 unmodified lines
116117def 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.124124 Example::125 .. code-block:: python126126 @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!'133134 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!"135136 .. versionadded:: 0.9137 """140 ctx = _cv_request.get(None)138 ctx = _cv_app.get(None)139142 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 lines
150F = t.TypeVar("F", bound=t.Callable[..., t.Any])151152153def 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.157162 Example::158 .. warning::159160 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.163164 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.168169 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.173174 .. code-block:: python175176 import gevent177 from flask import copy_current_request_context178179 @app.route('/')
7 unmodified lines
187 return 'Regular response'188189 .. versionadded:: 0.10190 """179 ctx = _cv_request.get(None)191 ctx = _cv_app.get(None)192193 if ctx is None:194 raise RuntimeError(195 "'copy_current_request_context' can only be used when a"
9 unmodified lines
205 return update_wrapper(wrapper, f) # type: ignore[return-value]206207208def 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.210202 ::211 .. code-block:: python212204 class User(db.Model):213 from flask import has_request_context, request214206 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_addr217212 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.221215 class User(db.Model):222 .. code-block:: python223217 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 request225226 if request:227 remote_addr = request.remote_addr228229 .. versionadded:: 0.7230 """225 return _cv_request.get(None) is not None231 return (ctx := _cv_app.get(None)) is not None and ctx.has_request232233234def 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.237233 .. versionadded:: 0.9234 """235 return _cv_app.get(None) is not None238 .. code-block:: python239240 from flask import has_app_context, g241238class 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 = ...244245 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.248251 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 g250256 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 = ...253267 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 None257272 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)258274 def __enter__(self) -> AppContext:275 self.push()276 return self259class 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.265278 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.269270 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`.273287class 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.279293 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.284297 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.288301 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.293294 .. versionchanged:: 3.2295 The session is loaded the first time it is accessed, rather than when296 the context is pushed.297 """298299 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 """310311 self.g: _AppCtxGlobals = app.app_ctx_globals_class()312 """The global data for this context. Accessed through :data:`.g`."""313314 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 """318319 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]] = []323324 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 = e329333 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."""332337 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 """337344 .. 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.341342 :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)348349 @property350 def has_request(self) -> bool:351 """True if this context was created with request data."""352 return self._request is not None353354 def copy(self) -> te.Self:355 """Create a new context with the same data objects as this context. See356 :func:`.copy_current_request_context`.357358 .. 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.360361 .. 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 )368369 @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.")377378 return self._request379380 @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.")388389 if self._session is None:390 si = self.app.session_interface391 self._session = si.open_session(self.app, self.request)392393 if self._session is None:394 self._session = si.make_null_session(self.app)395396 return self._session397398 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]408409 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.413372 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.416378 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 += 1422380 # 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 return425388 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)428391 # 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()431396 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.435436 Typically, this is not used directly. Instead, use a ``with`` block437 to manage the context.438439 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.444445 :param exc: An unhandled exception that was raised while the context was446 active. Passed to teardown functions.447448 .. 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.")453406 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)455412 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 )460420 # 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 )466425 if app_ctx is not None:426 app_ctx.pop(exc)467 self._push_count -= 1468428 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 return471472 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)481433 def __enter__(self) -> RequestContext:482 def __enter__(self) -> te.Self:483 self.push()484 return self485486 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)493494 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 )500501 return f"<{type(self).__name__} {id(self)} of {self.app.name}>"502503504def __getattr__(name: str) -> t.Any:505 import warnings506507 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 AppContext515516 raise AttributeError(name)
modified:src/flask/debughelpers.py+4 added-3 removed
4 unmodified lines
5from jinja2.loaders import BaseLoader6from werkzeug.routing import RequestRedirect78from .blueprints import Blueprint9from .globals import request_ctx9from .globals import _cv_app10from .sansio.app import App1112if t.TYPE_CHECKING:13 from .sansio.scaffold import Scaffold
121 unmodified lines
135 """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.blueprint139140 if (ctx := _cv_app.get(None)) is not None and ctx.has_request:141 blueprint = ctx.request.blueprint142143 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 lines
modified:src/flask/globals.py+44 added-18 removed
7 unmodified lines
8if 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 Request1415 T = t.TypeVar("T", covariant=True)1617 class ProxyMixin(t.Protocol[T]):18 def _get_current_object(self) -> T: ...1920 # 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): ...2324 class AppContextProxy(ProxyMixin[AppContext], AppContext): ...2526 class _AppCtxGlobalsProxy(ProxyMixin[_AppCtxGlobals], _AppCtxGlobals): ...2728 class RequestProxy(ProxyMixin[Request], Request): ...2930 class SessionMixinProxy(ProxyMixin[SessionMixin], SessionMixin): ...313233_no_app_msg = """\34Working outside of application context.3520This typically means that you attempted to use functionality that needed21the current application. To solve this, set up an application context22with app.app_context(). See the documentation for more information.\36Attempted to use functionality that expected a current application to be set. To37solve this, set up an app context using 'with app.app_context()'. See the38documentation on app context for more information.\39"""40_cv_app: ContextVar[AppContext] = ContextVar("flask.app_ctx")25app_ctx: AppContext = LocalProxy( # type: ignore[assignment]41app_ctx: AppContextProxy = LocalProxy( # type: ignore[assignment]42 _cv_app, unbound_message=_no_app_msg43)28current_app: Flask = LocalProxy( # type: ignore[assignment]44current_app: FlaskProxy = LocalProxy( # type: ignore[assignment]45 _cv_app, "app", unbound_message=_no_app_msg46)31g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment]47g: _AppCtxGlobalsProxy = LocalProxy( # type: ignore[assignment]48 _cv_app, "g", unbound_message=_no_app_msg49)5051_no_req_msg = """\52Working outside of request context.5338This typically means that you attempted to use functionality that needed39an active HTTP request. Consult the documentation on testing for40information about how to avoid this problem.\54Attempted to use functionality that expected an active HTTP request. See the55documentation on request context for more information.\56"""42_cv_request: ContextVar[RequestContext] = ContextVar("flask.request_ctx")43request_ctx: RequestContext = LocalProxy( # type: ignore[assignment]44 _cv_request, unbound_message=_no_req_msg57request: RequestProxy = LocalProxy( # type: ignore[assignment]58 _cv_app, "request", unbound_message=_no_req_msg59)46request: Request = LocalProxy( # type: ignore[assignment]47 _cv_request, "request", unbound_message=_no_req_msg60session: SessionMixinProxy = LocalProxy( # type: ignore[assignment]61 _cv_app, "session", unbound_message=_no_req_msg62)49session: SessionMixin = LocalProxy( # type: ignore[assignment]50 _cv_request, "session", unbound_message=_no_req_msg51)636465def __getattr__(name: str) -> t.Any:66 import warnings6768 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_ctx7677 raise AttributeError(name)
modified:src/flask/helpers.py+22 added-28 removed
12 unmodified lines
13from werkzeug.utils import redirect as _wz_redirect14from werkzeug.wrappers import Response as BaseResponse1516from .globals import _cv_app17from .globals import _cv_request17from .globals import app_ctx18from .globals import current_app19from .globals import request20from .globals import request_ctx20from .globals import session21from .signals import message_flashed2223if t.TYPE_CHECKING: # pragma: no cover
38 unmodified lines
62def 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.6970 Use it as a decorator on a generator function:
39 unmodified lines
110111 return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]112113 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 )119121 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]122128 # 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()129138 # 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 lines
255 .. 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)261262 return _wz_redirect(location, code=code, Response=Response)263264
13 unmodified lines
278 .. 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)284285 _wz_abort(code, *args, **kwargs)286287
43 unmodified lines
331 # 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 lines
371 :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 flashes384385386def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:387 ctx = app_ctx._get_current_object()388389 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_age391392 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 kwargs399400
235 unmodified lines
modified:src/flask/templating.py+14 added-20 removed
6 unmodified lines
7from jinja2 import Template8from jinja2 import TemplateNotFound910from .globals import _cv_app11from .globals import _cv_request11from .globals import current_app13from .globals import request12from .helpers import stream_with_context13from .signals import before_render_template14from .signals import template_rendered15
6 unmodified lines
22def _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.session2829 if ctx is not None:30 rv["g"] = ctx.g3132 if ctx.has_request:33 rv["request"] = ctx.request34 rv["session"] = ctx.session3536 return rv373839class Environment(BaseEnvironment):
104 unmodified lines
144 :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)151152
3 unmodified lines
156157 :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)163164
10 unmodified lines
175 template_rendered.send(176 app, _async_wrapper=app.ensure_sync, template=template, context=context177 )178179 rv = generate()179 return stream_with_context(generate())180181 # If a request context is active, keep it while generating.182 if request:183 rv = stream_with_context(rv)181185 return rv186187182def stream_template(183 template_name_or_list: str | Template | list[str | Template],184 **context: t.Any,185) -> t.Iterator[str]:
6 unmodified lines
192 :param context: The variables to make available in the template.193194 .. 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)199200
6 unmodified lines
207 :param context: The variables to make available in the template.208209 .. 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 lines
106 return _werkzeug_version107108109class 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`.114115 .. versionchanged:: 0.12116 `app.test_client()` includes preset default environment, which can be117 set after instantiation of the `app.test_client()` object in
181 unmodified lines
modified:tests/conftest.py+9 added-8 removed
3 unmodified lines
4import pytest5from _pytest import monkeypatch67from flask import Flask8from flask.globals import request_ctx8from flask.globals import app_ctx as _app_ctx91011@pytest.fixture(scope="session", autouse=True)12def _standard_os_environ():
69 unmodified lines
828384@pytest.fixture(autouse=True)85def 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 yield8788 # 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()9195 assert leaks == []92 while _app_ctx:93 leaks.append(_app_ctx._get_current_object())94 _app_ctx.pop()9596 assert not leaks979899@pytest.fixture100def modules_tmp_path(tmp_path, monkeypatch):101 """A temporary directory added to sys.path."""102 rv = tmp_path / "modules_tmp"
27 unmodified lines
modified:tests/test_appctx.py+6 added-5 removed
1import pytest23import flask4from flask.globals import app_ctx5from flask.globals import request_ctx567def test_basic_url_generation(app):8 app.config["SERVER_NAME"] = "localhost"
96 unmodified lines
105106 with app.app_context():107 client.get("/")108109 # teardown request context, and with block context110 assert cleanup_stuff == [None]110 assert cleanup_stuff == [None, None]111112113def test_app_tearing_down_with_unhandled_exception(app, client):114 app.config["PROPAGATE_EXCEPTIONS"] = True
10 unmodified lines
125 with pytest.raises(ValueError, match="dummy"):126 with app.app_context():127 client.get("/")128129 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]134135136def test_app_ctx_globals_methods(app, app_ctx):137 # get
41 unmodified lines
179180 @app.route("/")181 def index():182 with app_ctx:181 with request_ctx:182 pass183 pass184185 assert flask.request.environ["werkzeug.request"] is not None186 return ""187
23 unmodified lines
modified:tests/test_reqctx.py+3 added-3 removed
1 unmodified line
23import pytest45import flask6from flask.globals import request_ctx6from flask.globals import app_ctx7from flask.sessions import SecureCookieSessionInterface8from flask.sessions import SessionInterface910try:
141 unmodified lines
152153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"156 reqctx = request_ctx.copy()156 ctx = app_ctx.copy()157158 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 lines
modified:tests/test_session_interface.py+2 added-2 removed
1import flask2from flask.globals import request_ctx2from flask.globals import app_ctx3from flask.sessions import SessionInterface456def test_open_session_with_endpoint():
6 unmodified lines
13 def save_session(self, app, session, response):14 pass1516 def open_session(self, app, request):17 request_ctx.match_request()17 app_ctx.match_request()18 assert request.endpoint is not None1920 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()
7 unmodified lines
modified:tests/test_testing.py+2 added-2 removed
4 unmodified lines
56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo9from flask.globals import _cv_request9from flask.globals import _cv_app10from flask.json import jsonify11from flask.testing import EnvironBuilder12from flask.testing import FlaskCliRunner13
367 unmodified lines
381382 # 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_ctx
modified:CHANGES.rst+4 added
3 unmodified lines
4Unreleased56- 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`1415
1624 unmodified lines