Flask Signals Signal API
Flask uses the Blinker library to send signals when key events occur. You can connect these signals to perform additional logging, monitoring, and other operations.
Signals are not a core feature of Flask—most needs can be met through hooks (before_request, etc.).
Core request signals
| Signal | Trigger Timing | Arguments passed |
|---|---|---|
| request_started | After the request context is established, before preprocessing | sender=app |
| request_finished | After the response is built, before it is sent | sender=app, response |
| got_request_exception | An unhandled exception occurs during request processing | sender=app, exception |
| request_tearing_down | When the request context is destroyed (always executed) | sender=app, exc (optional) |
Application context signals
| Signal | Trigger Timing | Arguments passed |
|---|---|---|
| appcontext_pushed | When the application context is pushed onto the stack | sender=app |
| appcontext_popped | When the application context is popped from the stack | sender=app |
| appcontext_tearing_down | When the application context is destroyed (always executed) | sender=app, exc (optional) |
Template and message signals
| Signal | Trigger Timing | Arguments passed |
|---|---|---|
| template_rendered | When template rendering succeeds | sender=app, template, context |
| before_render_template | Before template rendering | sender=app, template, context |
| message_flashed | When flash() is called | sender=app, message, category |
Ways to connect signals
| Method | Description |
|---|---|
| signal.connect(func, app) | Connect the signal directly. func receives sender and keyword arguments |
| signal.connect_via(app)(func) | Decorator form. Automatically passes app as the sender |
| with signal.connected_to(func, app): | Context manager. Temporarily connect the signal |
Code Example
Example
from
flask
import
Flask
,
request_started
,
request_finished
,
template_rendered
app
=
Flask
(
name
)
Method 1: Direct connection
def
log_request_start
(
sender
,
**extra
)
:
(
f
"Request started on {sender.name}"
)
request_started.
connect
(
log_request_start
,
app
)
Method 2: Decorator connection
@
request_finished.
connect_via
(
app
)
def
log_request_end
(
sender
,
response
,
**extra
)
:
(
f
"Request finished with status {response.status_code}"
)
Method 3: Template rendering signal
@
template_rendered.
connect_via
(
app
)
def
log_template
(
sender
,
template
,
context
,
**extra
)
:
(
f
"Template rendered: {template.name}"
)
Method 4: Catch exceptions
from
flask
import
got_request_exception
def
log_error
(
sender
,
exception
,
**extra
)
:
sender.
logger
.
error
(
f
"Exception: {exception}"
)
got_request_exception.
connect
(
log_error
,
app
)