0
# Application and Routing
1
2
Core application management and URL routing functionality including the main Bottle class, route decorators, URL parameter handling, and application mounting.
3
4
## Capabilities
5
6
### Application Class
7
8
The Bottle class represents a web application instance with routes, configuration, plugins, and error handlers.
9
10
```python { .api }
11
class Bottle:
12
def __init__(self, **kwargs):
13
"""
14
Create a new Bottle application.
15
16
Parameters:
17
- **kwargs: deprecated catchall and autojson options
18
"""
19
20
@property
21
def config(self) -> ConfigDict:
22
"""Application configuration dictionary."""
23
24
@property
25
def routes(self) -> list:
26
"""List of installed Route instances."""
27
28
@property
29
def router(self) -> Router:
30
"""Router instance for request matching."""
31
32
def run(self, **kwargs):
33
"""Start development server with this application."""
34
35
def wsgi(self, environ, start_response):
36
"""
37
WSGI interface for the application.
38
39
Parameters:
40
- environ: dict, WSGI environment
41
- start_response: callable, WSGI start_response function
42
43
Returns:
44
iterator: response iterator
45
"""
46
47
def mount(self, prefix, app, **options):
48
"""
49
Mount another WSGI application or Bottle instance.
50
51
Parameters:
52
- prefix: str, URL prefix for mounted app
53
- app: WSGI application or Bottle instance
54
- **options: mount options
55
"""
56
57
def merge(self, routes):
58
"""
59
Merge routes from another application.
60
61
Parameters:
62
- routes: list or Bottle, routes to merge
63
"""
64
65
def add_hook(self, name, func):
66
"""
67
Add a hook callback.
68
69
Parameters:
70
- name: str, hook name
71
- func: callable, hook callback
72
"""
73
74
def reset(self, route=None):
75
"""
76
Reset routes and clear plugin cache."""
77
78
def close(self):
79
"""
80
Close application and clean up resources."""
81
```
82
83
### Route Registration
84
85
Register URL patterns with handler functions using decorators or direct method calls.
86
87
```python { .api }
88
def route(path=None, method='GET', callback=None, **options):
89
"""
90
Register a route with the default application.
91
92
Parameters:
93
- path: str, URL pattern (e.g., '/hello/<name>')
94
- method: str, HTTP method ('GET', 'POST', etc.)
95
- callback: function, handler function (when used directly)
96
- **options: route options (name, apply, skip, etc.)
97
98
Returns:
99
function: decorator function or Route instance
100
"""
101
102
def get(path=None, callback=None, **options):
103
"""Register a GET route. Equivalent to route(path, method='GET')."""
104
105
def post(path=None, callback=None, **options):
106
"""Register a POST route. Equivalent to route(path, method='POST')."""
107
108
def put(path=None, callback=None, **options):
109
"""Register a PUT route. Equivalent to route(path, method='PUT')."""
110
111
def delete(path=None, callback=None, **options):
112
"""Register a DELETE route. Equivalent to route(path, method='DELETE')."""
113
114
def patch(path=None, callback=None, **options):
115
"""Register a PATCH route. Equivalent to route(path, method='PATCH')."""
116
```
117
118
For Bottle application instances, use the same methods:
119
120
```python { .api }
121
class Bottle:
122
def route(self, path=None, method='GET', callback=None, **options): ...
123
def get(self, path=None, method='GET', **options): ...
124
def post(self, path=None, method='POST', **options): ...
125
def put(self, path=None, method='PUT', **options): ...
126
def delete(self, path=None, method='DELETE', **options): ...
127
def patch(self, path=None, method='PATCH', **options): ...
128
```
129
130
### URL Parameters
131
132
Extract parameters from URL patterns using angle bracket syntax.
133
134
Usage examples:
135
136
```python
137
@route('/hello/<name>')
138
def hello(name):
139
return f'Hello {name}!'
140
141
@route('/user/<id:int>')
142
def show_user(id):
143
return f'User ID: {id}'
144
145
@route('/static/<filepath:path>')
146
def serve_static(filepath):
147
return static_file(filepath, root='/static/')
148
```
149
150
Supported filters:
151
- `:int` - matches integers
152
- `:float` - matches floating point numbers
153
- `:path` - matches paths including slashes
154
- `:re[...]` - matches regular expressions
155
156
### Error Handling
157
158
Register error handlers for HTTP status codes.
159
160
```python { .api }
161
def error(code=500, callback=None):
162
"""
163
Register an error handler for HTTP status codes.
164
165
Parameters:
166
- code: int, HTTP status code (404, 500, etc.)
167
- callback: function, error handler function
168
169
Returns:
170
function: decorator function
171
"""
172
173
class Bottle:
174
def error(self, code=500, callback=None): ...
175
```
176
177
Usage:
178
179
```python
180
@error(404)
181
def error_404(error):
182
return 'Page not found!'
183
184
@error(500)
185
def error_500(error):
186
return 'Internal server error!'
187
```
188
189
### Application Mounting
190
191
Mount sub-applications or WSGI applications at URL prefixes.
192
193
```python { .api }
194
def mount(prefix, app, **options):
195
"""
196
Mount an application at a URL prefix.
197
198
Parameters:
199
- prefix: str, URL prefix (e.g., '/api')
200
- app: Bottle or WSGI application
201
- **options: mounting options
202
"""
203
204
class Bottle:
205
def mount(self, prefix, app, **options): ...
206
```
207
208
### URL Generation
209
210
Generate URLs for named routes.
211
212
```python { .api }
213
def url(routename, **kwargs):
214
"""
215
Generate URL for a named route.
216
217
Parameters:
218
- routename: str, name of the route
219
- **kwargs: URL parameters
220
221
Returns:
222
str: generated URL
223
"""
224
225
class Bottle:
226
def get_url(self, routename, **kwargs): ...
227
```
228
229
### Application Stack
230
231
Global application management for module-level shortcuts.
232
233
```python { .api }
234
class AppStack(list):
235
"""Stack of Bottle applications for module-level shortcuts."""
236
def __call__(self):
237
"""Return the current default application."""
238
239
def push(self, app=None):
240
"""Push new application to stack."""
241
242
# Global instances
243
app: AppStack # Current default application stack
244
default_app: AppStack # Alias for app
245
apps: AppStack # Alias for app
246
```
247
248
## Route Configuration
249
250
### Route Objects
251
252
Individual route mappings with metadata and configuration.
253
254
```python { .api }
255
class Route:
256
def __init__(self, app, rule, method, callback, **options):
257
"""
258
Create a route instance.
259
260
Parameters:
261
- app: Bottle, parent application
262
- rule: str, URL pattern
263
- method: str, HTTP method
264
- callback: function, handler function
265
- **options: route configuration
266
"""
267
268
@property
269
def rule(self) -> str:
270
"""URL pattern for this route."""
271
272
@property
273
def method(self) -> str:
274
"""HTTP method for this route."""
275
276
@property
277
def callback(self):
278
"""Handler function for this route."""
279
280
@property
281
def name(self) -> str:
282
"""Route name for URL building."""
283
284
@property
285
def plugins(self) -> list:
286
"""List of plugins applied to this route."""
287
288
@property
289
def skiplist(self) -> set:
290
"""Set of plugins to skip for this route."""
291
292
@property
293
def config(self) -> dict:
294
"""Route configuration dictionary."""
295
296
def get_undecorated_callback(self):
297
"""Get original callback if decorated."""
298
299
def get_callback_args(self):
300
"""Get callback function argument names."""
301
302
def get_config(self, key, default=None):
303
"""Get route configuration value."""
304
305
def reset(self):
306
"""Reset route and clear plugin cache."""
307
308
def prepare(self):
309
"""Prepare route for execution (apply plugins)."""
310
```
311
312
### Router
313
314
Maps HTTP requests to routes with URL parameter extraction.
315
316
```python { .api }
317
class Router:
318
def add(self, rule, method, target, **options):
319
"""
320
Add a route to the router.
321
322
Parameters:
323
- rule: str, URL pattern
324
- method: str, HTTP method
325
- target: any, route target (usually Route instance)
326
- **options: router options
327
"""
328
329
def match(self, path, method='GET'):
330
"""
331
Match request path and method to a route.
332
333
Parameters:
334
- path: str, request path
335
- method: str, HTTP method
336
337
Returns:
338
tuple: (target, url_args) or (None, None)
339
"""
340
```