0
# Blueprint System
1
2
Blueprints provide a modular way to organize Sanic applications by grouping related routes, middleware, and functionality into reusable components. They enable clean separation of concerns and support nested blueprint structures for complex applications.
3
4
## Capabilities
5
6
### Blueprint Creation
7
8
Create blueprint instances with customizable configuration and organizational features.
9
10
```python { .api }
11
class Blueprint:
12
def __init__(
13
self,
14
name: str,
15
url_prefix: str = None,
16
host: str = None,
17
version: int = None,
18
strict_slashes: bool = None,
19
version_prefix: str = "/v",
20
ctx: Any = None,
21
):
22
"""
23
Create a new blueprint.
24
25
Parameters:
26
- name: Blueprint name
27
- url_prefix: URL prefix for all routes
28
- host: Host restriction for blueprint
29
- version: API version number
30
- strict_slashes: Strict slash handling
31
- version_prefix: Version URL prefix
32
- ctx: Blueprint context object
33
"""
34
```
35
36
### Blueprint Routing
37
38
Define routes within blueprints using the same decorators as the main application.
39
40
```python { .api }
41
def route(
42
self,
43
uri: str,
44
methods: list = None,
45
host: str = None,
46
strict_slashes: bool = None,
47
stream: bool = False,
48
version: int = None,
49
name: str = None,
50
**kwargs
51
):
52
"""
53
Blueprint route decorator.
54
55
Parameters:
56
- uri: Route path
57
- methods: HTTP methods
58
- host: Host restriction
59
- strict_slashes: Slash handling
60
- stream: Enable streaming
61
- version: Route version
62
- name: Route name
63
"""
64
65
def get(self, uri: str, **kwargs):
66
"""GET method decorator."""
67
68
def post(self, uri: str, **kwargs):
69
"""POST method decorator."""
70
71
def put(self, uri: str, **kwargs):
72
"""PUT method decorator."""
73
74
def delete(self, uri: str, **kwargs):
75
"""DELETE method decorator."""
76
77
def patch(self, uri: str, **kwargs):
78
"""PATCH method decorator."""
79
80
def head(self, uri: str, **kwargs):
81
"""HEAD method decorator."""
82
83
def options(self, uri: str, **kwargs):
84
"""OPTIONS method decorator."""
85
86
def add_route(
87
self,
88
handler,
89
uri: str,
90
methods: list = None,
91
**kwargs
92
):
93
"""
94
Add route programmatically.
95
96
Parameters:
97
- handler: Route handler function
98
- uri: Route path
99
- methods: HTTP methods
100
"""
101
```
102
103
### Blueprint WebSocket Support
104
105
Define WebSocket endpoints within blueprints.
106
107
```python { .api }
108
def websocket(self, uri: str, **kwargs):
109
"""
110
WebSocket decorator for blueprints.
111
112
Parameters:
113
- uri: WebSocket path
114
- **kwargs: WebSocket options
115
"""
116
117
def add_websocket_route(self, handler, uri: str, **kwargs):
118
"""
119
Add WebSocket route programmatically.
120
121
Parameters:
122
- handler: WebSocket handler
123
- uri: WebSocket path
124
"""
125
```
126
127
### Blueprint Static Files
128
129
Serve static files through blueprints with blueprint-specific configuration.
130
131
```python { .api }
132
def static(
133
self,
134
uri: str,
135
file_or_directory: str,
136
**kwargs
137
):
138
"""
139
Serve static files from blueprint.
140
141
Parameters:
142
- uri: Static file URL path
143
- file_or_directory: File or directory path
144
- **kwargs: Static file options
145
"""
146
```
147
148
### Blueprint Middleware
149
150
Apply middleware specifically to blueprint routes.
151
152
```python { .api }
153
def middleware(self, middleware_or_request: str):
154
"""
155
Blueprint middleware decorator.
156
157
Parameters:
158
- middleware_or_request: Middleware type ('request' or 'response')
159
"""
160
```
161
162
### Blueprint Event Listeners
163
164
Register event listeners that execute during blueprint lifecycle events.
165
166
```python { .api }
167
def listener(self, event: str):
168
"""
169
Blueprint event listener decorator.
170
171
Parameters:
172
- event: Event name
173
"""
174
```
175
176
### Blueprint Exception Handlers
177
178
Define exception handlers specific to blueprint routes.
179
180
```python { .api }
181
def exception(self, *exceptions):
182
"""
183
Blueprint exception handler decorator.
184
185
Parameters:
186
- *exceptions: Exception classes to handle
187
"""
188
```
189
190
### Blueprint Groups
191
192
Group multiple blueprints together for bulk operations and shared configuration.
193
194
```python { .api }
195
class BlueprintGroup:
196
def __init__(
197
self,
198
url_prefix: str = None,
199
version: int = None,
200
strict_slashes: bool = None,
201
version_prefix: str = "/v",
202
):
203
"""
204
Create blueprint group.
205
206
Parameters:
207
- url_prefix: Shared URL prefix
208
- version: Shared version
209
- strict_slashes: Shared slash handling
210
- version_prefix: Shared version prefix
211
"""
212
213
def append(self, blueprint: Blueprint):
214
"""
215
Add blueprint to group.
216
217
Parameters:
218
- blueprint: Blueprint to add
219
"""
220
221
def extend(self, blueprints: list):
222
"""
223
Add multiple blueprints to group.
224
225
Parameters:
226
- blueprints: List of blueprints
227
"""
228
229
def insert(self, index: int, blueprint: Blueprint):
230
"""
231
Insert blueprint at specific position.
232
233
Parameters:
234
- index: Insert position
235
- blueprint: Blueprint to insert
236
"""
237
238
def remove(self, blueprint: Blueprint):
239
"""
240
Remove blueprint from group.
241
242
Parameters:
243
- blueprint: Blueprint to remove
244
"""
245
246
def middleware(self, middleware_or_request: str):
247
"""
248
Apply middleware to all blueprints in group.
249
250
Parameters:
251
- middleware_or_request: Middleware type
252
"""
253
254
def exception(self, *exceptions):
255
"""
256
Apply exception handler to all blueprints in group.
257
258
Parameters:
259
- *exceptions: Exception classes
260
"""
261
```
262
263
## Usage Examples
264
265
### Basic Blueprint
266
267
```python
268
from sanic import Blueprint
269
from sanic.response import json
270
271
# Create blueprint
272
api_v1 = Blueprint("api_v1", url_prefix="/api/v1")
273
274
@api_v1.route("/users")
275
async def get_users(request):
276
users = await fetch_users()
277
return json({"users": users})
278
279
@api_v1.route("/users", methods=["POST"])
280
async def create_user(request):
281
user_data = request.json
282
user = await create_user(user_data)
283
return json({"user": user}, status=201)
284
285
# Register blueprint with app
286
app.blueprint(api_v1)
287
```
288
289
### Blueprint with Middleware
290
291
```python
292
from sanic import Blueprint
293
from sanic.response import json
294
295
admin_bp = Blueprint("admin", url_prefix="/admin")
296
297
@admin_bp.middleware("request")
298
async def check_admin_auth(request):
299
"""Ensure user has admin privileges."""
300
if not await is_admin(request):
301
return json({"error": "Admin access required"}, status=403)
302
303
@admin_bp.route("/dashboard")
304
async def admin_dashboard(request):
305
return json({"message": "Admin dashboard"})
306
307
app.blueprint(admin_bp)
308
```
309
310
### Blueprint Groups
311
312
```python
313
from sanic import Blueprint, Sanic
314
from sanic.blueprints import BlueprintGroup
315
316
# Create individual blueprints
317
users_bp = Blueprint("users", url_prefix="/users")
318
orders_bp = Blueprint("orders", url_prefix="/orders")
319
products_bp = Blueprint("products", url_prefix="/products")
320
321
# Group blueprints with shared configuration
322
api_group = BlueprintGroup(url_prefix="/api/v1")
323
api_group.append(users_bp)
324
api_group.append(orders_bp)
325
api_group.append(products_bp)
326
327
# Register entire group
328
app.blueprint(api_group)
329
```
330
331
### Nested Blueprints
332
333
```python
334
# Main API blueprint
335
api = Blueprint("api", url_prefix="/api")
336
337
# Sub-blueprints for different versions
338
v1 = Blueprint("v1", url_prefix="/v1")
339
v2 = Blueprint("v2", url_prefix="/v2")
340
341
@v1.route("/users")
342
async def v1_users(request):
343
return json({"version": "1.0", "users": []})
344
345
@v2.route("/users")
346
async def v2_users(request):
347
return json({"version": "2.0", "users": [], "metadata": {}})
348
349
# Create group and register
350
api_versions = BlueprintGroup()
351
api_versions.append(v1)
352
api_versions.append(v2)
353
354
app.blueprint(api_versions)
355
```