API Reference¶
This is a mostly auto-generated API. If you are new to bottle, you might find the narrative Documentation more helpful.
Module Contents¶
The module defines several functions, constants, and an exception.
-
debug
(mode=True)[source]¶ Change the debug level. There is only one debug level supported at the moment.
-
run
(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs)[source]¶ Start a server instance. This method blocks until the server terminates.
Parameters: - app – WSGI application or target string supported by
load_app()
. (default:default_app()
) - server – Server adapter to use. See
server_names
keys for valid names or pass aServerAdapter
subclass. (default: wsgiref) - host – Server address to bind to. Pass
0.0.0.0
to listens on all interfaces including the external one. (default: 127.0.0.1) - port – Server port to bind to. Values below 1024 require root privileges. (default: 8080)
- reloader – Start auto-reloading server? (default: False)
- interval – Auto-reloader interval in seconds (default: 1)
- quiet – Suppress output to stdout and stderr? (default: False)
- options – Options passed to the server adapter.
- app – WSGI application or target string supported by
-
load_app
(target)[source]¶ Load a bottle application based on a target string and return the application object.
If the target is an import path (e.g. package.module), the application stack is used to isolate the routes defined in that module. If the target contains a colon (e.g. package.module:myapp) the module variable specified after the colon is returned instead.
-
request
= <bottle.Request object>¶ A thread-save instance of
Request
representing the current request.
-
response
= <bottle.Response object>¶ A thread-save instance of
Response
used to build the HTTP response.
-
HTTP_CODES
= {200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 418: "I'm a teapot", 100: 'Continue', 101: 'Switching Protocols', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: '(Unused)', 307: 'Temporary Redirect', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported'}¶ A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)
-
app
()¶ -
default_app
()¶ Return the current Default Application. Actually, these are callable instances of
AppStack
and implement a stack-like API.
-
class
AppStack
[source]¶ A stack-like list. Calling it returns the head of the stack.
-
pop
()¶ Return the current default application and remove it from the stack.
-
Routing¶
Bottle maintains a stack of Bottle
instances (see app()
and AppStack
) and uses the top of the stack as a default application for some of the module-level functions and decorators.
-
route
(path, method='GET', callback=None, **options)¶ -
get
(...)¶ -
post
(...)¶ -
put
(...)¶ -
delete
(...)¶ Decorator to install a route to the current default application. See
Bottle.route()
for details.
-
error
(...)¶ Decorator to install an error handler to the current default application. See
Bottle.error()
for details.
WSGI and HTTP Utilities¶
-
parse_auth
(header)[source]¶ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
Encode and sign a pickle-able object. Return a (byte) string
Verify and decode an encoded string. Return an object or None.
Return True if the argument looks like a encoded cookie.
-
yieldroutes
(func)[source]¶ Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:
a() -> '/a' b(x, y) -> '/b/:x/:y' c(x, y=5) -> '/c/:x' and '/c/:x/:y' d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
-
path_shift
(script_name, path_info, shift=1)[source]¶ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
Returns: The modified paths.
Parameters: - script_name – The SCRIPT_NAME path.
- script_name – The PATH_INFO path.
- shift – The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
Data Structures¶
-
class
WSGIHeaderDict
(environ)[source]¶ This dict-like class wraps a WSGI environ dict and provides convenient access to HTTP_* fields. Keys and values are native strings (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI environment contains non-native string values, these are de- or encoded using a lossless ‘latin1’ character set.
The API will remain stable even on changes to the relevant PEPs. Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one that uses non-native strings.)
The Bottle
Class¶
-
class
Bottle
(catchall=True, autojson=True, config=None)[source]¶ WSGI application
-
mount
(app, prefix, **options)[source]¶ Mount an application to a specific URL prefix. The prefix is added to SCIPT_PATH and removed from PATH_INFO before the sub-application is called.
Parameters: - app – an instance of
Bottle
. - prefix – path prefix used as a mount-point.
All other parameters are passed to the underlying
route()
call.- app – an instance of
-
install
(plugin)[source]¶ Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the
Plugin
API.
-
uninstall
(plugin)[source]¶ Uninstall plugins. Pass an instance to remove a specific plugin. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching
name
attribute. PassTrue
to remove all plugins. The list of affected plugins is returned.
-
reset
(id=None)[source]¶ Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.
-
match
(environ)[source]¶ (deprecated) Search for a matching route and return a (callback, urlargs) tuple. The first element is the associated route callback with plugins applied. The second value is a dictionary with parameters extracted from the URL. The
Router
raisesHTTPError
(404/405) on a non-match.
-
route
(path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config)[source]¶ A decorator to bind a function to a request URL. Example:
@app.route('/hello/:name') def hello(name): return 'Hello %s' % name
The
:name
part is a wildcard. SeeRouter
for syntax details.Parameters: - path – Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function.
- method – HTTP method (GET, POST, PUT, ...) or a list of methods to listen to. (default: GET)
- callback – An optional shortcut to avoid the decorator
syntax.
route(..., callback=func)
equalsroute(...)(func)
- name – The name for this route. (default: None)
- apply – A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins.
- skip – A list of plugins, plugin classes or names. Matching
plugins are not installed to this route.
True
skips all.
Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see
Plugin.apply()
).
-
delete
(path=None, method='DELETE', **options)[source]¶ Equals
route()
with aDELETE
method parameter.
-
handle
(path, method='GET')[source]¶ (deprecated) Execute the first matching route callback and return the result.
HTTPResponse
exceptions are catched and returned. IfBottle.catchall
is true, other exceptions are catched as well and returned asHTTPError
instances (500).
-
HTTP Request
and Response
objects¶
The Request
class wraps a WSGI environment and provides helpful methods to parse and access form data, cookies, file uploads and other metadata. Most of the attributes are read-only.
The Response
class on the other hand stores header and cookie data that is to be sent to the client.
Note
You usually don’t instantiate Request
or Response
yourself, but use the module-level instances bottle.request
and bottle.response
only. These hold the context for the current request cycle and are updated on every request. Their attributes are thread-local, so it is safe to use the global instance in multi-threaded environments too.
-
class
Request
(environ=None)[source]¶ Represents a single HTTP request using thread-local attributes. The Request object wraps a WSGI environment and can be used as such.
-
bind
(environ)[source]¶ Bind a new WSGI environment.
This is done automatically for the global bottle.request instance on every request.
-
path_shift
(shift=1)[source]¶ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
Parameters: shift – The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
-
urlparts
[source]¶ Return a
urlparse.SplitResult
tuple that can be used to reconstruct the full URL as requested by the client. The tuple contains: (scheme, host, path, query_string, fragment). The fragment is always empty because it is not visible to the server.
-
url
¶ Full URL as requested by the client.
-
fullpath
¶ Request path including SCRIPT_NAME (if present).
-
query_string
¶ The part of the URL following the ‘?’.
-
content_length
¶ Content-Length header as an integer, -1 if not specified
-
headers
[source]¶ Request HTTP Headers stored in a
HeaderDict
.
-
POST
[source]¶ The combined values from
forms
andfiles
. Values are either strings (form values) or instances ofcgi.FieldStorage
(file uploads).
-
forms
[source]¶ POST form values parsed into an instance of
MultiDict
.This property contains form values parsed from an url-encoded or multipart/form-data encoded POST request bidy. The values are native strings.
-
files
[source]¶ File uploads parsed into an instance of
MultiDict
.This property contains file uploads parsed from an multipart/form-data encoded POST request body. The values are instances of
cgi.FieldStorage
.
-
auth
¶ HTTP authorization data as a (user, passwd) tuple. (experimental)
This implementation currently only supports basic auth and returns None on errors.
-
COOKIES
[source]¶ Cookies parsed into a dictionary. Signed cookies are NOT decoded automatically. See
get_cookie()
for details.
Return the content of a cookie. To read a Signed Cookies, use the same secret as used to create the cookie (see
Response.set_cookie()
). If anything goes wrong, None is returned.
-
is_ajax
¶ True if the request was generated using XMLHttpRequest
-
-
class
Response
[source]¶ Represents a single HTTP response using thread-local attributes.
-
headerlist
¶ Returns a wsgi conform list of header/value pairs.
-
charset
¶ Return the charset specified in the content-type header.
This defaults to UTF-8.
-
COOKIES
¶ A dict-like SimpleCookie instance. Use
set_cookie()
instead.
Add a cookie or overwrite an old one. If the secret parameter is set, create a Signed Cookie (described below).
Parameters: - key – the name of the cookie.
- value – the value of the cookie.
- secret – required for signed cookies. (default: None)
- max_age – maximum age in seconds. (default: None)
- expires – a datetime object or UNIX timestamp. (defaut: None)
- domain – the domain that is allowed to read the cookie. (default: current domain)
- path – limits the cookie to a given path (default: /)
If neither expires nor max_age are set (default), the cookie lasts only as long as the browser is not closed.
Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side.
Delete a cookie. Be sure to use the same domain and path parameters as used to create the cookie.
-
content_type
¶ Current ‘Content-Type’ header.
-
Templates¶
All template engines supported by bottle
implement the BaseTemplate
API. This way it is possible to switch and mix template engines without changing the application code at all.
-
class
BaseTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶ Base class and minimal API for template adapters
-
__init__
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter stores a list containing directory paths. The encoding parameter should be used to decode byte strings or files. The settings parameter contains a dict for engine-specific settings.
-
classmethod
search
(name, lookup=[])[source]¶ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
-
classmethod
global_config
(key, *args)[source]¶ This reads or sets the global settings stored in class.settings.
-
prepare
(**options)[source]¶ Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.
-
render
(*args, **kwargs)[source]¶ Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (*args) or directly, as keywords (**kwargs).
-
-
view
(tpl_name, **defaults)[source]¶ Decorator: renders a template for a handler. The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters.
-
template
(*args, **kwargs)[source]¶ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).
You can write your own adapter for your favourite template engine or use one of the predefined adapters. Currently there are four fully supported template engines:
Class | URL | Decorator | Render function |
---|---|---|---|
SimpleTemplate |
SimpleTemplate Engine | view() |
template() |
MakoTemplate |
http://www.makotemplates.org | mako_view() |
mako_template() |
CheetahTemplate |
http://www.cheetahtemplate.org/ | cheetah_view() |
cheetah_template() |
Jinja2Template |
http://jinja.pocoo.org/ | jinja2_view() |
jinja2_template() |
To use MakoTemplate
as your default template engine, just import its specialised decorator and render function:
from bottle import mako_view as view, mako_template as template