From 39e8a2b99fd2bf4166ccfe23ab04bea6a7a6ff2d Mon Sep 17 00:00:00 2001 From: Hyunjun Kim Date: Wed, 11 Jan 2017 17:20:48 +0900 Subject: [PATCH] Signaling support with Blinker integration --- docs/signals.md | 27 +++++++++++++++++++++++++++ requirements.txt | 2 ++ sanic/sanic.py | 4 ++++ sanic/signals.py | 10 ++++++++++ 4 files changed, 43 insertions(+) create mode 100644 docs/signals.md create mode 100644 sanic/signals.py diff --git a/docs/signals.md b/docs/signals.md new file mode 100644 index 00000000..899d98c0 --- /dev/null +++ b/docs/signals.md @@ -0,0 +1,27 @@ +# Signals + +Signals allow you to send notifications to multiple subscribers when the specific event occured. +Signaling is provided by [Blinker](http://pythonhosted.org/blinker/) library and +Sanic has few built-in signals: + +* `request_started`: Sent when the request processing has started. +* `request_finished`: Sent when the request processing has finished. + +## Examples + +```python +from sanic.signals import request_started +import my_realtime_stat + +app = Sanic(__name__) + +@request_started.connect +def collect_stats(request): + my_realtime_stat.incoming_requests.incr(request.url) + + +@request_finished.connect +def count_errors(response): + if response.status != 200: + my_realtime_stat.error_responses.incr(response.status) +``` diff --git a/requirements.txt b/requirements.txt index cef8660e..41799297 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ httptools ujson uvloop aiofiles +multidict +blinker diff --git a/sanic/sanic.py b/sanic/sanic.py index 018ed720..b6f9f99e 100644 --- a/sanic/sanic.py +++ b/sanic/sanic.py @@ -13,6 +13,7 @@ from .log import log from .response import HTTPResponse from .router import Router from .server import serve, HttpProtocol +from .signals import request_started, request_finished from .static import register as static_register from .exceptions import ServerError from socket import socket, SOL_SOCKET, SO_REUSEADDR @@ -176,6 +177,8 @@ class Sanic: :return: Nothing """ try: + request_started.send(request) + # -------------------------------------------- # # Request Middleware # -------------------------------------------- # @@ -239,6 +242,7 @@ class Sanic: response = HTTPResponse( "An error occurred while handling an error") + request_finished.send(response) response_callback(response) # -------------------------------------------------------------------- # diff --git a/sanic/signals.py b/sanic/signals.py new file mode 100644 index 00000000..82bbefda --- /dev/null +++ b/sanic/signals.py @@ -0,0 +1,10 @@ +from blinker import Namespace + +__all__ = ('request_started', 'request_finished') + +_signals = Namespace() +signal = _signals.signal + + +request_started = signal('request-started') +request_finished = signal('request-finished')