Merge pull request #5058 from pallets/require-blinker
Before adoption: this commit came in with the history the project adopted, so no landing records it.
blinker is required, signals are always available
authored by David Lord · committed by GitHub · parents e1e4e82, 9cb1a7a · Browse files · 18 files·+77 added−163 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+77 added−163 removed
- tests:+0 added−17 removed
- other:+77 added−146 removed
Provenance
- Commit
a05c0c6- Tree
c93db92- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e1e4e82- Parent 2
9cb1a7a
18 files changed+77 added−163 removed
modified:docs/api.rst+5 added-23 removed
331 unmodified lines332 333 Signals334 -------335 336-.. versionadded:: 0.6336+Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.337 338-.. data:: signals.signals_available338+.. _blinker: https://blinker.readthedocs.io/339 340- ``True`` if the signaling system is available. This is the case341- when `blinker`_ is installed.342-343-The following signals exist in Flask:344-340 .. data:: template_rendered341 342 This signal is sent when a template was successfully rendered. The343 signal is invoked with the instance of the template as `template`157 unmodified lines501 :data:`appcontext_tearing_down` signal.502 503 .. versionadded:: 0.10504 510-505 .. data:: message_flashed506 507 This signal is sent when the application is flashing a message. The508 messages is sent as `message` keyword argument and the category as9 unmodified lines518 message_flashed.connect(record, app)519 520 .. versionadded:: 0.10521 528-.. class:: signals.Namespace522+.. data:: signals.signals_available523 530- An alias for :class:`blinker.base.Namespace` if blinker is available,531- otherwise a dummy class that creates fake signals. This class is532- available for Flask extensions that want to provide the same fallback533- system as Flask itself.524+ .. deprecated:: 2.3525+ Will be removed in Flask 2.4. Signals are always available526 535- .. method:: signal(name, doc=None)527 537- Creates a new signal for this namespace if blinker is available,538- otherwise returns a fake signal that has a send method that will539- do nothing but will fail with a :exc:`RuntimeError` for all other540- operations, including connecting.541-542-543-.. _blinker: https://pypi.org/project/blinker/544-545-528 Class-Based Views529 -----------------530 531 .. versionadded:: 0.7191 unmodified linesmodified:docs/appcontext.rst+4 added-6 removed
138 unmodified lines139 140 Events and Signals141 ------------------142 143-The application will call functions registered with144-:meth:`~Flask.teardown_appcontext` when the application context is145-popped.143+The application will call functions registered with :meth:`~Flask.teardown_appcontext`144+when the application context is popped.145 147-If :data:`~signals.signals_available` is true, the following signals are148-sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and149-:data:`appcontext_popped`.146+The following signals are sent: :data:`appcontext_pushed`,147+:data:`appcontext_tearing_down`, and :data:`appcontext_popped`.modified:docs/installation.rst+2 added-2 removed
22 unmodified lines23 * `ItsDangerous`_ securely signs data to ensure its integrity. This is used24 to protect Flask's session cookie.25 * `Click`_ is a framework for writing command line applications. It provides26 the ``flask`` command and allows adding custom management commands.27+* `Blinker`_ provides support for :doc:`signals`.28 29 .. _Werkzeug: https://palletsprojects.com/p/werkzeug/30 .. _Jinja: https://palletsprojects.com/p/jinja/31 .. _MarkupSafe: https://palletsprojects.com/p/markupsafe/32 .. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/33 .. _Click: https://palletsprojects.com/p/click/34+.. _Blinker: https://blinker.readthedocs.io/35 36 37 Optional dependencies38 ~~~~~~~~~~~~~~~~~~~~~39 40 These distributions will not be installed automatically. Flask will detect and41 use them if you install them.42 41-* `Blinker`_ provides support for :doc:`signals`.43 * `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``44 commands.45 * `Watchdog`_ provides a faster, more efficient reloader for the development46 server.47 47-.. _Blinker: https://blinker.readthedocs.io/en/stable/48 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme49 .. _watchdog: https://pythonhosted.org/watchdog/50 51 94 unmodified linesmodified:docs/reqcontext.rst+9 added-14 removed
202 unmodified lines203 204 Signals205 ~~~~~~~206 207-If :data:`~signals.signals_available` is true, the following signals are208-sent:207+The following signals are sent:208 210-#. :data:`request_started` is sent before the211- :meth:`~Flask.before_request` functions are called.209+#. :data:`request_started` is sent before the :meth:`~Flask.before_request` functions210+ are called.211+#. :data:`request_finished` is sent after the :meth:`~Flask.after_request` functions212+ are called.213+#. :data:`got_request_exception` is sent when an exception begins to be handled, but214+ before an :meth:`~Flask.errorhandler` is looked up or called.215+#. :data:`request_tearing_down` is sent after the :meth:`~Flask.teardown_request`216+ functions are called.217 213-#. :data:`request_finished` is sent after the214- :meth:`~Flask.after_request` functions are called.218 216-#. :data:`got_request_exception` is sent when an exception begins to217- be handled, but before an :meth:`~Flask.errorhandler` is looked up or218- called.219-220-#. :data:`request_tearing_down` is sent after the221- :meth:`~Flask.teardown_request` functions are called.222-223-219 .. _notes-on-proxies:220 221 Notes On Proxies222 ----------------21 unmodified linesmodified:docs/signals.rst+19 added-40 removed
1 Signals2 =======3 4-.. versionadded:: 0.64+Signals are a lightweight way to notify subscribers of certain events during the5+lifecycle of the application and each request. When an event occurs, it emits the6+signal, which calls each subscriber.7 6-Starting with Flask 0.6, there is integrated support for signalling in7-Flask. This support is provided by the excellent `blinker`_ library and8-will gracefully fall back if it is not available.8+Signals are implemented by the `Blinker`_ library. See its documentation for detailed9+information. Flask provides some built-in signals. Extensions may provide their own.10 10-What are signals? Signals help you decouple applications by sending11-notifications when actions occur elsewhere in the core framework or12-another Flask extensions. In short, signals allow certain senders to13-notify subscribers that something happened.11+Many signals mirror Flask's decorator-based callbacks with similar names. For example,12+the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request`13+decorator. The advantage of signals over handlers is that they can be subscribed to14+temporarily, and can't directly affect the application. This is useful for testing,15+metrics, auditing, and more. For example, if you want to know what templates were16+rendered at what parts of what requests, there is a signal that will notify you of that17+information.18 15-Flask comes with a couple of signals and other extensions might provide16-more. Also keep in mind that signals are intended to notify subscribers17-and should not encourage subscribers to modify data. You will notice that18-there are signals that appear to do the same thing like some of the19-builtin decorators do (eg: :data:`~flask.request_started` is very similar20-to :meth:`~flask.Flask.before_request`). However, there are differences in21-how they work. The core :meth:`~flask.Flask.before_request` handler, for22-example, is executed in a specific order and is able to abort the request23-early by returning a response. In contrast all signal handlers are24-executed in undefined order and do not modify any data.19 26-The big advantage of signals over handlers is that you can safely27-subscribe to them for just a split second. These temporary28-subscriptions are helpful for unit testing for example. Say you want to29-know what templates were rendered as part of a request: signals allow you30-to do exactly that.20+Core Signals21+------------22 23+See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle`24+page also describes the order that signals and decorators execute.25+26+27 Subscribing to Signals28 ----------------------29 30 To subscribe to a signal, you can use the62 unmodified lines93 with captured_templates(app, templates, **extra):94 ...95 template, context = templates[0]96 102-.. admonition:: Blinker API Changes103-104- The :meth:`~blinker.base.Signal.connected_to` method arrived in Blinker105- with version 1.1.106-97 Creating Signals98 ----------------99 100 If you want to use signals in your own application, you can use the11 unmodified lines112 The name for the signal here makes it unique and also simplifies113 debugging. You can access the name of the signal with the114 :attr:`~blinker.base.NamedSignal.name` attribute.115 126-.. admonition:: For Extension Developers127-128- If you are writing a Flask extension and you want to gracefully degrade for129- missing blinker installations, you can do so by using the130- :class:`flask.signals.Namespace` class.131-116 .. _signals-sending:117 118 Sending Signals119 ---------------33 unmodified lines153 154 Decorator Based Signal Subscriptions155 ------------------------------------156 173-With Blinker 1.1 you can also easily subscribe to signals by using the new157+You can also easily subscribe to signals by using the158 :meth:`~blinker.base.NamedSignal.connect_via` decorator::159 160 from flask import template_rendered161 162 @template_rendered.connect_via(app)163 def when_template_rendered(sender, template, context, **extra):164 print(f'Template {template.name} is rendered with {context}')165 182-Core Signals183-------------166 185-Take a look at :ref:`core-signals-list` for a list of all builtin signals.186-187-167 .. _blinker: https://pypi.org/project/blinker/modified:examples/javascript/pyproject.toml+1 added-1 removed
9 unmodified lines101112131414151617188 unmodified lines9 unmodified lines[project.urls]Documentation = "https://flask.palletsprojects.com/patterns/jquery/"
[project.optional-dependencies]test = ["pytest", "blinker"]test = ["pytest"]
[build-system]requires = ["setuptools"]build-backend = "setuptools.build_meta"8 unmodified linesmodified:requirements/build.txt-2 removed
9 unmodified lines10 packaging==23.011 # via build12 pyproject-hooks==1.0.013 # via build14-tomli==2.0.115- # via buildmodified:requirements/tests-pallets-min.in+1 added
1 unmodified line2 Jinja2==3.0.03 MarkupSafe==2.0.04 itsdangerous==2.0.05 click==8.0.06+blinker==1.6.2modified:requirements/tests-pallets-min.txt+3 added-1 removed
1-# SHA1:4de7d9e6254a945fd97ec10880dd23b6cd43b70d1+# SHA1:575f86f45391b662630a6080f0a12676215eb0cf2 #3 # This file is autogenerated by pip-compile-multi4 # To update, run:5 #6 # pip-compile-multi7 #8+blinker==1.6.29+ # via -r requirements/tests-pallets-min.in10 click==8.0.011 # via -r requirements/tests-pallets-min.in12 itsdangerous==2.0.013 # via -r requirements/tests-pallets-min.in8 unmodified linesmodified:requirements/tests.in-1 removed
1 pytest2 asgiref3-blinker3 greenlet ; python_version < "3.11"4 python-dotenv>=1; python_version >= "3.8"modified:requirements/tests.txt+1 added-11 removed
1-# SHA1:30698f5f4f9cba5088318306829a15b0dc123b381+# SHA1:3c8dde35aba20388b22430b17974af8ef8205b4f2 #3 # This file is autogenerated by pip-compile-multi4 # To update, run:5 #6 # pip-compile-multi7 #8 asgiref==3.6.09 # via -r requirements/tests.in10-blinker==1.6.111- # via -r requirements/tests.in12-exceptiongroup==1.1.113- # via pytest14-greenlet==2.0.2 ; python_version < "3.11"15- # via -r requirements/tests.in10 iniconfig==2.0.011 # via pytest12 packaging==23.013 # via pytest2 unmodified lines16 pytest==7.3.017 # via -r requirements/tests.in18 python-dotenv==1.0.0 ; python_version >= "3.8"19 # via -r requirements/tests.in26-tomli==2.0.127- # via pytest28-typing-extensions==4.5.029- # via blinkermodified:requirements/typing.txt-2 removed
13 unmodified lines14 mypy-extensions==1.0.015 # via mypy16 pycparser==2.2117 # via cffi18-tomli==2.0.119- # via mypy18 types-contextvars==2.4.7.219 # via -r requirements/typing.in20 types-dataclasses==0.6.621 # via -r requirements/typing.in4 unmodified linesmodified:src/flask/__init__.py+11 added-1 removed
30 unmodified lines31 from .signals import message_flashed as message_flashed32 from .signals import request_finished as request_finished33 from .signals import request_started as request_started34 from .signals import request_tearing_down as request_tearing_down35-from .signals import signals_available as signals_available35 from .signals import template_rendered as template_rendered36 from .templating import render_template as render_template37 from .templating import render_template_string as render_template_string38 from .templating import stream_template as stream_template48 unmodified lines87 stacklevel=2,88 )89 return Markup90 91+ if name == "signals_available":92+ import warnings93+94+ warnings.warn(95+ "'signals_available' is deprecated and will be removed in Flask 2.4."96+ " Signals are always available",97+ DeprecationWarning,98+ stacklevel=2,99+ )100+ return True101+102 raise AttributeError(name)modified:src/flask/signals.py+18 added-41 removed
1+from __future__ import annotations2+3 import typing as t4+import warnings5 3-try:4- from blinker import Namespace6+from blinker import Namespace7 6- signals_available = True7-except ImportError:8- signals_available = False9-10- class Namespace: # type: ignore11- def signal(self, name: str, doc: t.Optional[str] = None) -> "_FakeSignal":12- return _FakeSignal(name, doc)13-14- class _FakeSignal:15- """If blinker is unavailable, create a fake class with the same16- interface that allows sending of signals but will fail with an17- error on anything else. Instead of doing anything on send, it18- will just ignore the arguments and do nothing instead.19- """20-21- def __init__(self, name: str, doc: t.Optional[str] = None) -> None:22- self.name = name23- self.__doc__ = doc24-25- def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:26- pass27-28- def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.Any:29- raise RuntimeError(30- "Signalling support is unavailable because the blinker"31- " library is not installed."32- ) from None33-34- connect = connect_via = connected_to = temporarily_connected_to = _fail35- disconnect = _fail36- has_receivers_for = receivers_for = _fail37- del _fail38-39-40-# The namespace for code signals. If you are not Flask code, do41-# not put signals in here. Create your own namespace instead.8+# This namespace is only for signals provided by Flask itself.9 _signals = Namespace()10 44-45-# Core signals. For usage examples grep the source code or consult46-# the API documentation in docs/api.rst as well as docs/signals.rst11 template_rendered = _signals.signal("template-rendered")12 before_render_template = _signals.signal("before-render-template")13 request_started = _signals.signal("request-started")14 request_finished = _signals.signal("request-finished")2 unmodified lines17 appcontext_tearing_down = _signals.signal("appcontext-tearing-down")18 appcontext_pushed = _signals.signal("appcontext-pushed")19 appcontext_popped = _signals.signal("appcontext-popped")20 message_flashed = _signals.signal("message-flashed")21+22+23+def __getattr__(name: str) -> t.Any:24+ if name == "signals_available":25+ warnings.warn(26+ "The 'signals_available' attribute is deprecated and will be removed in"27+ " Flask 2.4. Signals are always available.",28+ DeprecationWarning,29+ stacklevel=2,30+ )31+ return True32+33+ raise AttributeError(name)modified:tests/test_signals.py-11 removed
1-import pytest2-3-try:4- import blinker5-except ImportError:6- blinker = None7-1 import flask2 10-pytestmark = pytest.mark.skipif(11- blinker is None, reason="Signals require the blinker library."12-)3 14-4 def test_template_rendered(app, client):5 @app.route("/")6 def index():7 return flask.render_template("simple_template.html", whiskey=42)174 unmodified linesmodified:tests/test_testing.py-6 removed
8 unmodified lines9 from flask.json import jsonify10 from flask.testing import EnvironBuilder11 from flask.testing import FlaskCliRunner12 13-try:14- import blinker15-except ImportError:16- blinker = None13 18-14 def test_environ_defaults_from_config(app, client):15 app.config["SERVER_NAME"] = "example.com:1234"16 app.config["APPLICATION_ROOT"] = "/foo"17 261 unmodified lines279 assert rv.is_json280 assert rv.get_json() == json_data281 282 288-@pytest.mark.skipif(blinker is None, reason="blinker is not installed")283 def test_client_json_no_app_context(app, client):284 @app.route("/hello", methods=["POST"])285 def hello():286 return f"Hello, {flask.request.json['name']}!"111 unmodified linesmodified:CHANGES.rst+2 added
26 unmodified lines27 directly from ``markupsafe`` instead. :pr:`4996`28 - The ``app.got_first_request`` property is deprecated. :pr:`4997`29 - The ``locked_cached_property`` decorator is deprecated. Use a lock inside the30 decorated function if locking is needed. :issue:`4993`31+- Signals are always available. ``blinker>=1.6.2`` is a required dependency. The32+ ``signals_available`` attribute is deprecated. :issue:`5056`33 - Remove uses of locks that could cause requests to block each other very briefly.34 :issue:`4993`35 - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.36 :pr:`4947`1436 unmodified linesmodified:pyproject.toml+1 added-1 removed
22 unmodified lines23 "Werkzeug>=2.2.2",24 "Jinja2>=3.0",25 "itsdangerous>=2.0",26 "click>=8.0",27+ "blinker>=1.6.2",28 "importlib-metadata>=3.6.0; python_version < '3.10'",29 ]30 dynamic = ["version"]31 58 unmodified lines90 91 [[tool.mypy.overrides]]92 module = [93 "asgiref.*",93- "blinker.*",94 "dotenv.*",95 "cryptography.*",96 "importlib_metadata",97 ]1 unmodified line