Fast and simple WSGI micro web-framework for small web applications with no dependencies other than the Python Standard Library.
npx @tessl/cli install tessl/pypi-bottle@0.13.00
# Bottle
1
2
A fast, simple and lightweight WSGI micro web-framework for Python distributed as a single file module with no dependencies other than the Python Standard Library. Bottle provides comprehensive web application functionality including request dispatching with URL parameter support, a built-in template engine, convenient utilities for handling form data, file uploads, cookies, and HTTP metadata, and a built-in HTTP development server.
3
4
## Package Information
5
6
- **Package Name**: bottle
7
- **Language**: Python
8
- **Installation**: `pip install bottle`
9
10
## Core Imports
11
12
```python
13
import bottle
14
```
15
16
Common usage patterns:
17
18
```python
19
from bottle import Bottle, route, run, request, response
20
```
21
22
Application shortcut functions:
23
24
```python
25
from bottle import route, get, post, put, delete, patch
26
```
27
28
## Basic Usage
29
30
```python
31
from bottle import route, run, template
32
33
@route('/hello/<name>')
34
def index(name):
35
return template('<b>Hello {{name}}</b>!', name=name)
36
37
run(host='localhost', port=8080)
38
```
39
40
Object-oriented approach:
41
42
```python
43
from bottle import Bottle
44
45
app = Bottle()
46
47
@app.route('/hello')
48
def hello():
49
return "Hello World!"
50
51
if __name__ == '__main__':
52
app.run(host='localhost', port=8080)
53
```
54
55
## Architecture
56
57
Bottle follows a minimalist design philosophy with several key components:
58
59
- **Bottle Application**: Core application object managing routes, plugins, and configuration
60
- **Router**: Maps incoming requests to handler functions with URL parameter extraction
61
- **Request/Response**: Thread-local objects providing access to HTTP request/response data
62
- **Template Engine**: Built-in templating with support for external engines (Jinja2, Mako, Cheetah)
63
- **Plugin System**: Extensible architecture for adding functionality like JSON handling, authentication
64
- **Server Adapters**: Support for various WSGI servers from development to production deployment
65
66
This design enables rapid development of small to medium web applications while maintaining the flexibility to scale and integrate with the broader Python web ecosystem.
67
68
## Capabilities
69
70
### Application and Routing
71
72
Core application management and URL routing functionality including the main Bottle class, route decorators, and URL parameter handling.
73
74
```python { .api }
75
class Bottle:
76
def __init__(self, **kwargs): ...
77
def route(self, path=None, method='GET', callback=None, **options): ...
78
def get(self, path=None, method='GET', **options): ...
79
def post(self, path=None, method='POST', **options): ...
80
def put(self, path=None, method='PUT', **options): ...
81
def delete(self, path=None, method='DELETE', **options): ...
82
def patch(self, path=None, method='PATCH', **options): ...
83
def run(self, **kwargs): ...
84
85
# Module-level shortcuts for default app
86
def route(path=None, method='GET', callback=None, **options): ...
87
def get(path=None, callback=None, **options): ...
88
def post(path=None, callback=None, **options): ...
89
def put(path=None, callback=None, **options): ...
90
def delete(path=None, callback=None, **options): ...
91
def patch(path=None, callback=None, **options): ...
92
```
93
94
[Application and Routing](./application-routing.md)
95
96
### Request Handling
97
98
Request object providing access to HTTP request data including headers, query parameters, form data, file uploads, cookies, and JSON data.
99
100
```python { .api }
101
class BaseRequest:
102
@property
103
def method(self) -> str: ...
104
@property
105
def path(self) -> str: ...
106
@property
107
def query(self) -> FormsDict: ...
108
@property
109
def forms(self) -> FormsDict: ...
110
@property
111
def files(self) -> FormsDict: ...
112
@property
113
def json(self) -> Any: ...
114
@property
115
def headers(self) -> HeaderDict: ...
116
@property
117
def cookies(self) -> SimpleCookie: ...
118
def get_header(self, name, default=None): ...
119
def get_cookie(self, key, default=None, secret=None): ...
120
121
# Global request instance
122
request: LocalRequest
123
```
124
125
[Request Handling](./request-handling.md)
126
127
### Response Management
128
129
Response object for setting HTTP response properties including status codes, headers, cookies, and content type.
130
131
```python { .api }
132
class BaseResponse:
133
@property
134
def status(self) -> int: ...
135
@property
136
def headers(self) -> HeaderDict: ...
137
@property
138
def content_type(self) -> str: ...
139
def set_header(self, name, value): ...
140
def add_header(self, name, value): ...
141
def get_header(self, name, default=None): ...
142
def set_cookie(self, key, value, **options): ...
143
def delete_cookie(self, key, **kwargs): ...
144
145
# Global response instance
146
response: LocalResponse
147
```
148
149
[Response Management](./response-management.md)
150
151
### Template Rendering
152
153
Built-in template engine with support for external template systems and template rendering functions.
154
155
```python { .api }
156
def template(name, **kwargs):
157
"""
158
Render a template with keyword arguments.
159
160
Parameters:
161
- name: str, template name or template string
162
- **kwargs: template variables
163
164
Returns:
165
str: rendered template
166
"""
167
168
def view(tpl_name, **defaults):
169
"""
170
Decorator that renders a template with the return value of the wrapped function.
171
172
Parameters:
173
- tpl_name: str, template name
174
- **defaults: default template variables
175
176
Returns:
177
function: decorator function
178
"""
179
180
class SimpleTemplate:
181
def __init__(self, source, **options): ...
182
def render(self, **kwargs): ...
183
```
184
185
[Template Rendering](./template-rendering.md)
186
187
### Static Files and Utilities
188
189
Static file serving, HTTP utilities, and helper functions for common web development tasks.
190
191
```python { .api }
192
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
193
"""
194
Serve static files with proper MIME types and caching headers.
195
196
Parameters:
197
- filename: str, file name to serve
198
- root: str, root directory path
199
- mimetype: str, MIME type ('auto' for automatic detection)
200
- download: bool, force download with Content-Disposition header
201
- charset: str, character encoding
202
203
Returns:
204
HTTPResponse: file response
205
"""
206
207
def abort(code=500, text='Unknown Error.'):
208
"""Raise an HTTPError with specified status code and message."""
209
210
def redirect(url, code=None):
211
"""Raise an HTTPResponse that redirects to the specified URL."""
212
```
213
214
[Static Files and Utilities](./static-utilities.md)
215
216
### Server Management
217
218
Development server and production server adapter support for various WSGI servers.
219
220
```python { .api }
221
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, debug=False, reloader=False, **kwargs):
222
"""
223
Start a development server.
224
225
Parameters:
226
- app: Bottle or WSGI application
227
- server: str, server adapter name
228
- host: str, server host
229
- port: int, server port
230
- debug: bool, enable debug mode
231
- reloader: bool, enable auto-reload
232
- **kwargs: additional server options
233
"""
234
235
class ServerAdapter:
236
def __init__(self, host='127.0.0.1', port=8080, **options): ...
237
def run(self, handler): ...
238
```
239
240
[Server Management](./server-management.md)
241
242
### Plugin System
243
244
Plugin architecture for extending Bottle functionality with custom middleware and request/response processing.
245
246
```python { .api }
247
class Bottle:
248
def install(self, plugin): ...
249
def uninstall(self, plugin): ...
250
def hook(self, name): ...
251
252
# Module-level shortcuts
253
def install(plugin): ...
254
def uninstall(plugin): ...
255
def hook(name): ...
256
```
257
258
[Plugin System](./plugin-system.md)
259
260
## Core Types
261
262
```python { .api }
263
class FormsDict(MultiDict):
264
"""Dictionary for form data with multiple values per key and unicode handling."""
265
def get(self, key, default=None, index=-1, type=None): ...
266
def getall(self, key): ...
267
def getunicode(self, name, default=None, encoding=None): ...
268
269
class MultiDict:
270
"""Dictionary allowing multiple values per key."""
271
def get(self, key, default=None, index=-1, type=None): ...
272
def getall(self, key): ...
273
def append(self, key, value): ...
274
275
class HeaderDict(MultiDict):
276
"""Case-insensitive dictionary for HTTP headers."""
277
278
class ConfigDict(dict):
279
"""Configuration dictionary with validation and change listeners."""
280
def load_config(self, filename): ...
281
def load_dict(self, source, namespace=''): ...
282
def load_module(self, path, namespace='', squash=True): ...
283
def meta_get(self, key, metafield, default=None): ...
284
def meta_set(self, key, metafield, value): ...
285
286
class FileUpload:
287
"""File upload wrapper with save functionality."""
288
@property
289
def name(self) -> str: ...
290
@property
291
def filename(self) -> str: ...
292
@property
293
def file(self): ...
294
@property
295
def headers(self) -> HeaderDict: ...
296
def save(self, destination, overwrite=False, chunk_size=65536): ...
297
298
class HTTPResponse(Exception):
299
"""HTTP response that can be raised as an exception."""
300
def __init__(self, body='', status=None, headers=None, **more_headers): ...
301
302
class HTTPError(HTTPResponse):
303
"""HTTP error response exception."""
304
305
class Route:
306
"""Individual route mapping with callback and configuration."""
307
def __init__(self, app, rule, method, callback, **options): ...
308
def get_undecorated_callback(self): ...
309
def get_callback_args(self): ...
310
311
class WSGIHeaderDict(dict):
312
"""Dict-like wrapper for WSGI environ HTTP headers."""
313
314
class ResourceManager:
315
"""Manages search paths for application files and resources."""
316
def add_path(self, path): ...
317
def lookup(self, name): ...
318
def open(self, name, mode='r'): ...
319
```
320
321
## Exception Classes
322
323
```python { .api }
324
class BottleException(Exception):
325
"""Base class for all Bottle-specific exceptions."""
326
327
class RouteError(BottleException):
328
"""Base class for all routing related exceptions."""
329
330
class RouteReset(RouteError):
331
"""Forces route reset and plugin re-application when raised."""
332
333
class RouteSyntaxError(RouteError):
334
"""Raised when route parser encounters unsupported syntax."""
335
336
class RouteBuildError(RouteError):
337
"""Raised when route URL cannot be built."""
338
339
class PluginError(BottleException):
340
"""Raised for plugin-related errors."""
341
342
class MultipartError(ValueError):
343
"""Raised for multipart form data parsing errors."""
344
345
class TemplateError(BottleException):
346
"""Base class for template-related errors."""
347
```
348
349
## Module Constants
350
351
```python { .api }
352
__version__: str
353
"""Framework version string."""
354
355
DEBUG: bool
356
"""Global debug flag."""
357
358
TEMPLATE_PATH: list
359
"""Default template lookup paths."""
360
361
HTTP_CODES: dict
362
"""HTTP status code to message mappings."""
363
364
# Global objects
365
request: LocalRequest
366
"""Thread-local request object available in route handlers."""
367
368
response: LocalResponse
369
"""Thread-local response object available in route handlers."""
370
371
local: threading.local
372
"""Thread-local namespace for custom data."""
373
374
app: AppStack
375
"""Default application stack."""
376
377
ext: object
378
"""Virtual package namespace for extensions."""
379
```