A modern Python web server and web framework designed for high performance and speed using async/await syntax.
npx @tessl/cli install tessl/pypi-sanic@25.3.00
# Sanic
1
2
A modern Python 3.8+ web server and web framework designed for high performance and speed. Sanic leverages Python's async/await syntax for non-blocking, asynchronous request handling, making it exceptionally fast for web applications. It's ASGI compliant and includes comprehensive features for building scalable web APIs, microservices, and high-performance web applications.
3
4
## Package Information
5
6
- **Package Name**: sanic
7
- **Language**: Python
8
- **Installation**: `pip install sanic`
9
- **Python Requirements**: Python 3.8+
10
11
## Core Imports
12
13
```python
14
from sanic import Sanic
15
```
16
17
Common imports for web applications:
18
19
```python
20
from sanic import Sanic, Request, Blueprint
21
from sanic.response import json, text, html, redirect
22
from sanic.exceptions import NotFound, ServerError
23
```
24
25
## Basic Usage
26
27
```python
28
from sanic import Sanic
29
from sanic.response import json
30
31
app = Sanic("MyApp")
32
33
@app.route("/")
34
async def test(request):
35
return json({"hello": "world"})
36
37
@app.route("/user/<name>")
38
async def user(request, name):
39
return json({"user": name})
40
41
if __name__ == "__main__":
42
app.run(host="0.0.0.0", port=8000)
43
```
44
45
## Architecture
46
47
Sanic's async-first design provides exceptional performance through:
48
49
- **Async/Await Support**: Native Python async/await for non-blocking operations
50
- **ASGI Compliance**: Standard interface for asynchronous web servers and applications
51
- **Optimized Libraries**: Uses uvloop and ujson by default for maximum performance
52
- **Modular Design**: Blueprint system for organizing large applications
53
- **Middleware Pipeline**: Request/response processing pipeline for cross-cutting concerns
54
- **Signal System**: Event-driven programming with built-in and custom signals
55
56
The framework prioritizes speed and efficiency while maintaining developer-friendly APIs and comprehensive feature support.
57
58
## Capabilities
59
60
### Core Application
61
62
The main Sanic application class that handles routing, middleware, configuration, and server lifecycle. Provides decorators and methods for defining HTTP routes, WebSocket endpoints, and application behavior.
63
64
```python { .api }
65
class Sanic:
66
def __init__(self, name: str, **kwargs): ...
67
def route(self, uri: str, methods: list = None, **kwargs): ...
68
def get(self, uri: str, **kwargs): ...
69
def post(self, uri: str, **kwargs): ...
70
def put(self, uri: str, **kwargs): ...
71
def delete(self, uri: str, **kwargs): ...
72
def websocket(self, uri: str, **kwargs): ...
73
def middleware(self, middleware_or_request: str): ...
74
def run(self, host: str = "127.0.0.1", port: int = 8000, **kwargs): ...
75
```
76
77
[Core Application](./core-application.md)
78
79
### Request and Response Handling
80
81
Comprehensive request and response objects for handling HTTP communications, including request data parsing, response generation, and specialized response types for different content formats.
82
83
```python { .api }
84
class Request:
85
@property
86
def json(self): ...
87
@property
88
def form(self): ...
89
@property
90
def files(self): ...
91
@property
92
def args(self): ...
93
@property
94
def headers(self): ...
95
96
def json(body, **kwargs): ...
97
def text(body: str, **kwargs): ...
98
def html(body: str, **kwargs): ...
99
def raw(body: bytes, **kwargs): ...
100
def redirect(to: str, **kwargs): ...
101
def file(location: str, **kwargs): ...
102
def empty(**kwargs): ...
103
```
104
105
[Request and Response](./request-response.md)
106
107
### Blueprint System
108
109
Modular application organization system that allows grouping related routes, middleware, and functionality into reusable components. Supports nested blueprints and blueprint groups for complex application structures.
110
111
```python { .api }
112
class Blueprint:
113
def __init__(self, name: str, **kwargs): ...
114
def route(self, uri: str, **kwargs): ...
115
def middleware(self, middleware_or_request: str): ...
116
def static(self, uri: str, file_or_directory: str, **kwargs): ...
117
118
class BlueprintGroup:
119
def append(self, blueprint: Blueprint): ...
120
def insert(self, index: int, blueprint: Blueprint): ...
121
```
122
123
[Blueprint System](./blueprints.md)
124
125
### Configuration Management
126
127
Flexible configuration system supporting environment variables, configuration files, and programmatic configuration. Includes built-in configuration options for server behavior, security, and performance tuning.
128
129
```python { .api }
130
class Config:
131
def __init__(self, **kwargs): ...
132
def load_environment_vars(self, prefix: str = "SANIC_"): ...
133
def from_envvar(self, variable_name: str): ...
134
def from_pyfile(self, filename: str): ...
135
def update_config(self, config: dict): ...
136
```
137
138
[Configuration](./configuration.md)
139
140
### Exception Handling
141
142
Comprehensive exception system with HTTP status code exceptions, error handlers, and custom exception support. Provides both built-in exceptions for common HTTP errors and mechanisms for custom error handling.
143
144
```python { .api }
145
class SanicException(Exception): ...
146
class NotFound(SanicException): ...
147
class ServerError(SanicException): ...
148
class BadRequest(SanicException): ...
149
class Unauthorized(SanicException): ...
150
class Forbidden(SanicException): ...
151
152
def exception(exception_type): ... # decorator
153
```
154
155
[Exception Handling](./exceptions.md)
156
157
### Middleware and Signals
158
159
Request/response middleware pipeline and event-driven signal system for implementing cross-cutting concerns and responding to application lifecycle events.
160
161
```python { .api }
162
def middleware(middleware_or_request: str): ... # decorator
163
164
class Signal:
165
def send(self, *args, **kwargs): ...
166
async def send_async(self, *args, **kwargs): ...
167
```
168
169
[Middleware and Signals](./middleware-signals.md)
170
171
### WebSocket Support
172
173
Native WebSocket support for real-time, bidirectional communication between client and server. Includes WebSocket routing, connection management, and message handling.
174
175
```python { .api }
176
def websocket(uri: str, **kwargs): ... # decorator
177
178
class Websocket:
179
async def send(self, data): ...
180
async def recv(self): ...
181
async def ping(self, data: bytes = b""): ...
182
async def pong(self, data: bytes = b""): ...
183
```
184
185
[WebSocket Support](./websockets.md)
186
187
### Server and Deployment
188
189
Server configuration, deployment options, and production-ready features including multi-worker support, SSL/TLS configuration, and various server protocols.
190
191
```python { .api }
192
def run(host: str = "127.0.0.1", port: int = 8000, **kwargs): ...
193
def create_server(**kwargs): ...
194
def serve(**kwargs): ...
195
```
196
197
[Server and Deployment](./server-deployment.md)
198
199
## Types
200
201
```python { .api }
202
# Core type aliases
203
DefaultSanic = "Sanic[Config, SimpleNamespace]"
204
DefaultRequest = Request[DefaultSanic, SimpleNamespace]
205
206
# Middleware types
207
MiddlewareType = Callable[[Request, Callable], Awaitable[Optional[HTTPResponse]]]
208
209
# Listener types
210
ListenerType = Callable[[Sanic], Awaitable[None]]
211
212
# Handler types
213
RouteHandler = Callable[..., Awaitable[HTTPResponse]]
214
215
# Exception types
216
class SanicException(Exception): ...
217
class NotFound(SanicException): ...
218
class ServerError(SanicException): ...
219
class BadRequest(SanicException): ...
220
class Unauthorized(SanicException): ...
221
class Forbidden(SanicException): ...
222
class MethodNotAllowed(SanicException): ...
223
class InvalidHeader(SanicException): ...
224
class HeaderNotFound(SanicException): ...
225
class FileNotFound(SanicException): ...
226
class RangeNotSatisfiable(SanicException): ...
227
class InternalServerError(SanicException): ...
228
class ServiceUnavailable(SanicException): ...
229
class ExpectationFailed(SanicException): ...
230
231
# HTTP types
232
class HTTPMethod:
233
GET: str = "GET"
234
POST: str = "POST"
235
PUT: str = "PUT"
236
DELETE: str = "DELETE"
237
PATCH: str = "PATCH"
238
HEAD: str = "HEAD"
239
OPTIONS: str = "OPTIONS"
240
241
# Configuration and routing
242
class Config: ...
243
class Router: ...
244
class SignalRouter: ...
245
class ErrorHandler: ...
246
class Inspector: ...
247
class CertLoader: ...
248
249
# Union types for flexibility
250
from typing import Union, Optional, Callable, Any, AnyStr
251
```