Skip to content
Myr

blinker is required, signals are always available

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 e1e4e82 · 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

18 files+77 added−163 removed

modified:docs/api.rst+5 added-23 removed
331 unmodified lines
332333Signals334-------335336.. versionadded:: 0.6336Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.337338.. data:: signals.signals_available338.. _blinker: https://blinker.readthedocs.io/339340 ``True`` if the signaling system is available. This is the case341 when `blinker`_ is installed.342343The following signals exist in Flask:344340.. data:: template_rendered341342 This signal is sent when a template was successfully rendered. The343 signal is invoked with the instance of the template as `template`
157 unmodified lines
501 :data:`appcontext_tearing_down` signal.502503 .. versionadded:: 0.10504510505.. data:: message_flashed506507 This signal is sent when the application is flashing a message. The508 messages is sent as `message` keyword argument and the category as
9 unmodified lines
518 message_flashed.connect(record, app)519520 .. versionadded:: 0.10521528.. class:: signals.Namespace522.. data:: signals.signals_available523530 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 available526535 .. method:: signal(name, doc=None)527537 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.541542543.. _blinker: https://pypi.org/project/blinker/544545528Class-Based Views529-----------------530531.. versionadded:: 0.7
191 unmodified lines
modified:docs/appcontext.rst+4 added-6 removed
138 unmodified lines
139140Events and Signals141------------------142143The application will call functions registered with144:meth:`~Flask.teardown_appcontext` when the application context is145popped.143The application will call functions registered with :meth:`~Flask.teardown_appcontext`144when the application context is popped.145147If :data:`~signals.signals_available` is true, the following signals are148sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and149:data:`appcontext_popped`.146The 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 lines
23* `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`.2829.. _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/353637Optional dependencies38~~~~~~~~~~~~~~~~~~~~~3940These distributions will not be installed automatically. Flask will detect and41use them if you install them.4241* `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.4747.. _Blinker: https://blinker.readthedocs.io/en/stable/48.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme49.. _watchdog: https://pythonhosted.org/watchdog/5051
94 unmodified lines
modified:docs/reqcontext.rst+9 added-14 removed
202 unmodified lines
203204Signals205~~~~~~~206207If :data:`~signals.signals_available` is true, the following signals are208sent:207The following signals are sent:208210#. :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.217213#. :data:`request_finished` is sent after the214 :meth:`~Flask.after_request` functions are called.218216#. :data:`got_request_exception` is sent when an exception begins to217 be handled, but before an :meth:`~Flask.errorhandler` is looked up or218 called.219220#. :data:`request_tearing_down` is sent after the221 :meth:`~Flask.teardown_request` functions are called.222223219.. _notes-on-proxies:220221Notes On Proxies222----------------
21 unmodified lines
modified:docs/signals.rst+19 added-40 removed
1Signals2=======34.. versionadded:: 0.64Signals are a lightweight way to notify subscribers of certain events during the5lifecycle of the application and each request. When an event occurs, it emits the6signal, which calls each subscriber.76Starting with Flask 0.6, there is integrated support for signalling in7Flask. This support is provided by the excellent `blinker`_ library and8will gracefully fall back if it is not available.8Signals are implemented by the `Blinker`_ library. See its documentation for detailed9information. Flask provides some built-in signals. Extensions may provide their own.1010What are signals? Signals help you decouple applications by sending11notifications when actions occur elsewhere in the core framework or12another Flask extensions. In short, signals allow certain senders to13notify subscribers that something happened.11Many signals mirror Flask's decorator-based callbacks with similar names. For example,12the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request`13decorator. The advantage of signals over handlers is that they can be subscribed to14temporarily, and can't directly affect the application. This is useful for testing,15metrics, auditing, and more. For example, if you want to know what templates were16rendered at what parts of what requests, there is a signal that will notify you of that17information.1815Flask comes with a couple of signals and other extensions might provide16more. Also keep in mind that signals are intended to notify subscribers17and should not encourage subscribers to modify data. You will notice that18there are signals that appear to do the same thing like some of the19builtin decorators do (eg: :data:`~flask.request_started` is very similar20to :meth:`~flask.Flask.before_request`). However, there are differences in21how they work. The core :meth:`~flask.Flask.before_request` handler, for22example, is executed in a specific order and is able to abort the request23early by returning a response. In contrast all signal handlers are24executed in undefined order and do not modify any data.1926The big advantage of signals over handlers is that you can safely27subscribe to them for just a split second. These temporary28subscriptions are helpful for unit testing for example. Say you want to29know what templates were rendered as part of a request: signals allow you30to do exactly that.20Core Signals21------------2223See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle`24page also describes the order that signals and decorators execute.252627Subscribing to Signals28----------------------2930To subscribe to a signal, you can use the
62 unmodified lines
93 with captured_templates(app, templates, **extra):94 ...95 template, context = templates[0]96102.. admonition:: Blinker API Changes103104 The :meth:`~blinker.base.Signal.connected_to` method arrived in Blinker105 with version 1.1.10697Creating Signals98----------------99100If you want to use signals in your own application, you can use the
11 unmodified lines
112The name for the signal here makes it unique and also simplifies113debugging. You can access the name of the signal with the114:attr:`~blinker.base.NamedSignal.name` attribute.115126.. admonition:: For Extension Developers127128 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.131116.. _signals-sending:117118Sending Signals119---------------
33 unmodified lines
153154Decorator Based Signal Subscriptions155------------------------------------156173With Blinker 1.1 you can also easily subscribe to signals by using the new157You can also easily subscribe to signals by using the158:meth:`~blinker.base.NamedSignal.connect_via` decorator::159160 from flask import template_rendered161162 @template_rendered.connect_via(app)163 def when_template_rendered(sender, template, context, **extra):164 print(f'Template {template.name} is rendered with {context}')165182Core Signals183------------166185Take a look at :ref:`core-signals-list` for a list of all builtin signals.186187167.. _blinker: https://pypi.org/project/blinker/
modified:examples/javascript/pyproject.toml+1 added-1 removed
modified:requirements/build.txt-2 removed
9 unmodified lines
10packaging==23.011 # via build12pyproject-hooks==1.0.013 # via build14tomli==2.0.115 # via build
modified:requirements/tests-pallets-min.in+1 added
1 unmodified line
2Jinja2==3.0.03MarkupSafe==2.0.04itsdangerous==2.0.05click==8.0.06blinker==1.6.2
modified: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#8blinker==1.6.29 # via -r requirements/tests-pallets-min.in10click==8.0.011 # via -r requirements/tests-pallets-min.in12itsdangerous==2.0.013 # via -r requirements/tests-pallets-min.in
8 unmodified lines
modified:requirements/tests.in-1 removed
1pytest2asgiref3blinker3greenlet ; python_version < "3.11"4python-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#8asgiref==3.6.09 # via -r requirements/tests.in10blinker==1.6.111 # via -r requirements/tests.in12exceptiongroup==1.1.113 # via pytest14greenlet==2.0.2 ; python_version < "3.11"15 # via -r requirements/tests.in10iniconfig==2.0.011 # via pytest12packaging==23.013 # via pytest
2 unmodified lines
16pytest==7.3.017 # via -r requirements/tests.in18python-dotenv==1.0.0 ; python_version >= "3.8"19 # via -r requirements/tests.in26tomli==2.0.127 # via pytest28typing-extensions==4.5.029 # via blinker
modified:requirements/typing.txt-2 removed
13 unmodified lines
14mypy-extensions==1.0.015 # via mypy16pycparser==2.2117 # via cffi18tomli==2.0.119 # via mypy18types-contextvars==2.4.7.219 # via -r requirements/typing.in20types-dataclasses==0.6.621 # via -r requirements/typing.in
4 unmodified lines
modified:src/flask/__init__.py+11 added-1 removed
30 unmodified lines
31from .signals import message_flashed as message_flashed32from .signals import request_finished as request_finished33from .signals import request_started as request_started34from .signals import request_tearing_down as request_tearing_down35from .signals import signals_available as signals_available35from .signals import template_rendered as template_rendered36from .templating import render_template as render_template37from .templating import render_template_string as render_template_string38from .templating import stream_template as stream_template
48 unmodified lines
87 stacklevel=2,88 )89 return Markup9091 if name == "signals_available":92 import warnings9394 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 True101102 raise AttributeError(name)
modified:src/flask/signals.py+18 added-41 removed
1from __future__ import annotations23import typing as t4import warnings53try:4 from blinker import Namespace6from blinker import Namespace76 signals_available = True7except ImportError:8 signals_available = False910 class Namespace: # type: ignore11 def signal(self, name: str, doc: t.Optional[str] = None) -> "_FakeSignal":12 return _FakeSignal(name, doc)1314 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 """2021 def __init__(self, name: str, doc: t.Optional[str] = None) -> None:22 self.name = name23 self.__doc__ = doc2425 def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:26 pass2728 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 None3334 connect = connect_via = connected_to = temporarily_connected_to = _fail35 disconnect = _fail36 has_receivers_for = receivers_for = _fail37 del _fail383940# 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()104445# Core signals. For usage examples grep the source code or consult46# the API documentation in docs/api.rst as well as docs/signals.rst11template_rendered = _signals.signal("template-rendered")12before_render_template = _signals.signal("before-render-template")13request_started = _signals.signal("request-started")14request_finished = _signals.signal("request-finished")
2 unmodified lines
17appcontext_tearing_down = _signals.signal("appcontext-tearing-down")18appcontext_pushed = _signals.signal("appcontext-pushed")19appcontext_popped = _signals.signal("appcontext-popped")20message_flashed = _signals.signal("message-flashed")212223def __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 True3233 raise AttributeError(name)
modified:tests/test_signals.py-11 removed
1import pytest23try:4 import blinker5except ImportError:6 blinker = None71import flask210pytestmark = pytest.mark.skipif(11 blinker is None, reason="Signals require the blinker library."12)3144def test_template_rendered(app, client):5 @app.route("/")6 def index():7 return flask.render_template("simple_template.html", whiskey=42)
174 unmodified lines
modified:tests/test_testing.py-6 removed
8 unmodified lines
9from flask.json import jsonify10from flask.testing import EnvironBuilder11from flask.testing import FlaskCliRunner1213try:14 import blinker15except ImportError:16 blinker = None131814def test_environ_defaults_from_config(app, client):15 app.config["SERVER_NAME"] = "example.com:1234"16 app.config["APPLICATION_ROOT"] = "/foo"17
261 unmodified lines
279 assert rv.is_json280 assert rv.get_json() == json_data281282288@pytest.mark.skipif(blinker is None, reason="blinker is not installed")283def 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 lines
modified:CHANGES.rst+2 added
26 unmodified lines
27 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 lines
modified:pyproject.toml+1 added-1 removed
22 unmodified lines
23 "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]30dynamic = ["version"]31
58 unmodified lines
9091[[tool.mypy.overrides]]92module = [93 "asgiref.*",93 "blinker.*",94 "dotenv.*",95 "cryptography.*",96 "importlib_metadata",97]
1 unmodified line