Overview
Sanic 22.6, released on July 1, 2022, adds background tasks and middleware priority.
Main Features
Background tasks
Background tasks execute asynchronous code independently from the request/response cycle, useful for periodic tasks.
python
from sanic import Sanic
import asyncio
app = Sanic('MyApp')
@app.before_server_start
async def setup(app, loop):
app.add_task(periodic_task())
async def periodic_task():
while True:
print('Checking...')
await asyncio.sleep(60)
Middleware priority
Middlewares can now be ordered by priority, providing fine-grained control over execution order.
python
from sanic import Sanic
app = Sanic('MyApp')
@app.middleware('request', priority=10)
async def auth_middleware(request):
# Executed first (high priority)
pass
@app.middleware('request', priority=1)
async def log_middleware(request):
# Executed after auth (low priority)
print(f'{request.method} {request.path}')
