What it is
Sanic is a Python 3.7+ web server and web framework that’s designed for fast HTTP responses using asynchronous capabilities powered by `asyncio`. It is ideal for building high-performance APIs and web applications.
Sanic allows defining routes with async request handlers, middleware, blueprints, and WebSocket support. It emphasizes high performance while maintaining simple and readable syntax.
Installation
pip install sanicGetting started
The smallest useful thing you can do with it, and what each part means.
from sanic import Sanic
from sanic.response import text
app = Sanic('my_app')
@app.get('/')
async def hello(request):
return text('Hello, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)from sanic import Sanic
from sanic.response import json
app = Sanic('my_app')
@app.get('/user/<name>')
async def greet_user(request, name):
return json({'message': f'Hello, {name}!'})
app.run(host='0.0.0.0', port=8000)Advanced usage
Where the library earns its place over a simpler alternative.
from sanic import Sanic
from sanic.response import text
app = Sanic('my_app')
@app.middleware('request')
async def print_request(request):
print(f'Received request: {request.method} {request.path}')
@app.get('/')
async def hello(request):
return text('Hello, Sanic!')
app.run(host='0.0.0.0', port=8000)from sanic import Sanic, Blueprint
from sanic.response import json
bp = Blueprint('api')
@bp.get('/status')
async def status(request):
return json({'status': 'ok'})
app = Sanic('my_app')
app.blueprint(bp, url_prefix='/api')
app.run(host='0.0.0.0', port=8000)from sanic import Sanic
from sanic.websocket import WebSocketProtocol
app = Sanic('my_app')
@app.websocket('/feed')
async def feed(request, ws):
while True:
data = await ws.recv()
await ws.send(f'Received: {data}')
app.run(host='0.0.0.0', port=8000, protocol=WebSocketProtocol)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- SanicException
- Use try/except blocks in handlers or Sanic’s error handlers to manage exceptions gracefully.
- Invalid usage of async/await
- Ensure all route handlers performing I/O operations are defined as async functions.
Best practices
- Use async request handlers to leverage non-blocking performance.
- Organize large applications using Blueprints for modular routing.
- Use middleware for authentication, logging, and request preprocessing.
- Leverage Sanic’s built-in support for HTTP/2 for improved speed.
- Monitor performance using Sanic’s built-in metrics or custom logging.
Background
Why it exists, and what it was reacting to.
Sanic was created by Kenneth Reitz in 2016 to provide an asynchronous Python web framework capable of handling high loads efficiently. It leverages Python's `async`/`await` syntax for non-blocking request handling and has been adopted for real-time APIs and web services requiring speed.
