Introduction to Sanic
Sanic is a modern asynchronous web framework for Python, built for creating high-performance web applications. Powered by asyncio, it efficiently handles thousands of concurrent connections thanks to its async/await syntax support. Sanic is ideal for building REST APIs, microservices, real-time applications, and high-load backends.
Key Features of Sanic
Performance and Architecture
Sanic is designed with speed in mind. The framework uses asyncio for asynchronous request handling, achieving performance comparable to Node.js and Go. Built-in async/await support makes your code cleaner and more efficient.
Feature Set
- Full async/await support out of the box
- Routing with parameters and middleware
- Built-in WebSocket support
- Template engine and static file handling
- CORS, cookies, and session support
- Simple and clean project structure
- Excellent scalability for API servers
Installation and Setup
Basic Installation
pip install sanic
Additional Dependencies
pip install sanic[ext] # Extensions
pip install jinja2 aiofiles python-dotenv
Creating Your First App
from sanic import Sanic
from sanic.response import text
app = Sanic("MyApp")
@app.get("/")
async def index(request):
return text("Hello from Sanic")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Routing and Request Handling
Basic Routes
@app.get("/")
async def get_handler(request):
return text("GET request")
@app.post("/")
async def post_handler(request):
return text("POST request")
@app.put("/")
async def put_handler(request):
return text("PUT request")
@app.delete("/")
async def delete_handler(request):
return text("DELETE request")
Async Routes
import asyncio
@app.get("/async")
async def async_route(request):
await asyncio.sleep(1) # Simulate an async operation
return text("Async response")
Working with Parameters and Data
Route Parameters
@app.get("/user/<user_id:int>")
async def get_user(request, user_id):
return text(f"User ID: {user_id}")
@app.get("/profile/<username:str>")
async def get_profile(request, username):
return text(f"Profile: {username}")
Query Parameters
@app.get("/search")
async def search(request):
query = request.args.get("q", "nothing")
limit = request.args.get("limit", "10")
return text(f"Search: {query}, limit: {limit}")
Handling JSON and Forms
from sanic.response import json
@app.post("/api/data")
async def receive_data(request):
data = request.json
return json({"received": data})
@app.post("/form")
async def handle_form(request):
username = request.form.get("username")
email = request.form.get("email")
return json({"username": username, "email": email})
Response Types
Different Response Formats
from sanic.response import text, json, html, redirect, file
@app.get("/text")
async def text_response(request):
return text("Plain text")
@app.get("/json")
async def json_response(request):
return json({"message": "JSON response"})
@app.get("/html")
async def html_response(request):
return html("<h1>HTML str