Overview
Sanic 21.3, released on March 15, 2021, introduces the Signals API for event-driven communication and improves route naming.
Main Features
Signals API
The Signals API lets you emit and listen to custom events in the application lifecycle. This is useful for decoupling business logic from route handlers.
python
from sanic import Sanic
from sanic.response import json
app = Sanic('MyApp')
# Listen to a custom signal
@app.signal('order.created')
async def on_order(order_id: str, **kwargs):
print(f'Order {order_id} created')
@app.post('/orders')
async def create_order(request):
order_id = '12345'
# Dispatch the signal
await app.dispatch('order.created', order_id=order_id)
return json({'id': order_id})
Route naming
The route naming system is improved: each route can be explicitly named and referenced via app.url_for() to reliably generate URLs.
python
from sanic import Sanic
from sanic.response import json, redirect
app = Sanic('MyApp')
@app.get('/users/<uid:int>', name='user_profile')
async def profile(request, uid):
return json({'id': uid, 'name': 'Alice'})
@app.get('/redirect/<uid:int>')
async def do_redirect(request, uid):
url = app.url_for('user_profile', uid=uid)
return redirect(url)
