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.

bottle.debug(mode=True)[source]

Change the debug level. There is only one debug level supported at the moment.

bottle.run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **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 a ServerAdapter 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.

bottle.load_app(target)[source]

Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See load() for the target parameter.

bottle.request = <LocalRequest: GET http://127.0.0.1/>

A thread-safe instance of LocalRequest. If accessed from within a request callback, this instance always refers to the current request (even on a multithreaded server).

bottle.response = Content-Type: text/html; charset=UTF-8

A thread-safe instance of LocalResponse. It is used to change the HTTP response for the current request.

bottle.HTTP_CODES = {HTTPStatus.CONTINUE: 'Continue', HTTPStatus.SWITCHING_PROTOCOLS: 'Switching Protocols', HTTPStatus.PROCESSING: 'Processing', HTTPStatus.EARLY_HINTS: 'Early Hints', HTTPStatus.OK: 'OK', HTTPStatus.CREATED: 'Created', HTTPStatus.ACCEPTED: 'Accepted', HTTPStatus.NON_AUTHORITATIVE_INFORMATION: 'Non-Authoritative Information', HTTPStatus.NO_CONTENT: 'No Content', HTTPStatus.RESET_CONTENT: 'Reset Content', HTTPStatus.PARTIAL_CONTENT: 'Partial Content', HTTPStatus.MULTI_STATUS: 'Multi-Status', HTTPStatus.ALREADY_REPORTED: 'Already Reported', HTTPStatus.IM_USED: 'IM Used', HTTPStatus.MULTIPLE_CHOICES: 'Multiple Choices', HTTPStatus.MOVED_PERMANENTLY: 'Moved Permanently', HTTPStatus.FOUND: 'Found', HTTPStatus.SEE_OTHER: 'See Other', HTTPStatus.NOT_MODIFIED: 'Not Modified', HTTPStatus.USE_PROXY: 'Use Proxy', HTTPStatus.TEMPORARY_REDIRECT: 'Temporary Redirect', HTTPStatus.PERMANENT_REDIRECT: 'Permanent Redirect', HTTPStatus.BAD_REQUEST: 'Bad Request', HTTPStatus.UNAUTHORIZED: 'Unauthorized', HTTPStatus.PAYMENT_REQUIRED: 'Payment Required', HTTPStatus.FORBIDDEN: 'Forbidden', HTTPStatus.NOT_FOUND: 'Not Found', HTTPStatus.METHOD_NOT_ALLOWED: 'Method Not Allowed', HTTPStatus.NOT_ACCEPTABLE: 'Not Acceptable', HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: 'Proxy Authentication Required', HTTPStatus.REQUEST_TIMEOUT: 'Request Timeout', HTTPStatus.CONFLICT: 'Conflict', HTTPStatus.GONE: 'Gone', HTTPStatus.LENGTH_REQUIRED: 'Length Required', HTTPStatus.PRECONDITION_FAILED: 'Precondition Failed', HTTPStatus.REQUEST_ENTITY_TOO_LARGE: 'Request Entity Too Large', HTTPStatus.REQUEST_URI_TOO_LONG: 'Request-URI Too Long', HTTPStatus.UNSUPPORTED_MEDIA_TYPE: 'Unsupported Media Type', HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: 'Requested Range Not Satisfiable', HTTPStatus.EXPECTATION_FAILED: 'Expectation Failed', HTTPStatus.IM_A_TEAPOT: "I'm a teapot", HTTPStatus.MISDIRECTED_REQUEST: 'Misdirected Request', HTTPStatus.UNPROCESSABLE_ENTITY: 'Unprocessable Entity', HTTPStatus.LOCKED: 'Locked', HTTPStatus.FAILED_DEPENDENCY: 'Failed Dependency', HTTPStatus.TOO_EARLY: 'Too Early', HTTPStatus.UPGRADE_REQUIRED: 'Upgrade Required', HTTPStatus.PRECONDITION_REQUIRED: 'Precondition Required', HTTPStatus.TOO_MANY_REQUESTS: 'Too Many Requests', HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE: 'Request Header Fields Too Large', HTTPStatus.UNAVAILABLE_FOR_LEGAL_REASONS: 'Unavailable For Legal Reasons', HTTPStatus.INTERNAL_SERVER_ERROR: 'Internal Server Error', HTTPStatus.NOT_IMPLEMENTED: 'Not Implemented', HTTPStatus.BAD_GATEWAY: 'Bad Gateway', HTTPStatus.SERVICE_UNAVAILABLE: 'Service Unavailable', HTTPStatus.GATEWAY_TIMEOUT: 'Gateway Timeout', HTTPStatus.HTTP_VERSION_NOT_SUPPORTED: 'HTTP Version Not Supported', HTTPStatus.VARIANT_ALSO_NEGOTIATES: 'Variant Also Negotiates', HTTPStatus.INSUFFICIENT_STORAGE: 'Insufficient Storage', HTTPStatus.LOOP_DETECTED: 'Loop Detected', HTTPStatus.NOT_EXTENDED: 'Not Extended', HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED: 'Network Authentication Required'}

A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)

bottle.app()
bottle.default_app()

Return the current Default Application. Actually, these are callable instances of AppStack and implement a stack-like API.

class bottle.AppStack(iterable=(), /)[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.

push(value=None)[source]

Add a new Bottle instance to 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.

bottle.route(path, method='GET', callback=None, **options)
bottle.get(...)
bottle.post(...)
bottle.put(...)
bottle.delete(...)

Decorator to install a route to the current default application. See Bottle.route() for details.

bottle.error(...)

Decorator to install an error handler to the current default application. See Bottle.error() for details.

WSGI and HTTP Utilities

bottle.parse_date(ims)[source]

Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.

bottle.parse_auth(header)[source]

Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None

bottle.cookie_encode(data, key)[source]

Encode and sign a pickle-able object. Return a (byte) string

bottle.cookie_decode(data, key)[source]

Verify and decode an encoded string. Return an object or None.

bottle.cookie_is_encoded(data)[source]

Return True if the argument looks like a encoded cookie.

bottle.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>'
bottle.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 bottle.MultiDict(*a, **k)[source]

This dict stores multiple values per key, but behaves exactly like a normal dict in that it returns only the newest value for any given key. There are special methods available to access the full list of values.

append(key, value)[source]

Add a new value to the list of values for this key.

get(key, default=None, index=-1, type=None)[source]

Return the most recent value for a key.

Parameters:
  • default – The default value to be returned if the key is not present or the type conversion fails.

  • index – An index for the list of available values.

  • type – If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned.

getall(key)[source]

Return a (possibly empty) list of values for a key.

getlist(key)

Return a (possibly empty) list of values for a key.

getone(key, default=None, index=-1, type=None)

Aliases for WTForms to mimic other multi-dict APIs (Django)

items() a set-like object providing a view on D's items[source]
iteritems()[source]

D.items() -> a set-like object providing a view on D’s items

iterkeys()[source]

D.keys() -> a set-like object providing a view on D’s keys

itervalues()[source]

D.values() -> an object providing a view on D’s values

keys() a set-like object providing a view on D's keys[source]
replace(key, value)[source]

Replace the list of values with a single value.

values() an object providing a view on D's values[source]
class bottle.HeaderDict(*a, **ka)[source]

A case-insensitive version of MultiDict that defaults to replace the old value instead of appending it.

append(key, value)[source]

Add a new value to the list of values for this key.

get(key, default=None, index=-1)[source]

Return the most recent value for a key.

Parameters:
  • default – The default value to be returned if the key is not present or the type conversion fails.

  • index – An index for the list of available values.

  • type – If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned.

getall(key)[source]

Return a (possibly empty) list of values for a key.

replace(key, value)[source]

Replace the list of values with a single value.

class bottle.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.)

cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')

List of keys that do not have a HTTP_ prefix.

keys() a set-like object providing a view on D's keys[source]
raw(key, default=None)[source]

Return the header value as is (may be bytes or unicode).

class bottle.AppStack(iterable=(), /)[source]

A stack-like list. Calling it returns the head of the stack.

push(value=None)[source]

Add a new Bottle instance to the stack

Exceptions

exception bottle.BottleException[source]

A base class for exceptions used by bottle.

exception bottle.HTTPResponse(body='', status=None, headers=None, **more_headers)[source]
exception bottle.HTTPError(status=None, body=None, exception=None, traceback=None, **options)[source]
exception bottle.RouteReset[source]

If raised by a plugin or request handler, the route is reset and all plugins are re-applied.

The Bottle Class

class bottle.Bottle(catchall=True, autojson=True)[source]

Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications.

Parameters:

catchall – If true (default), handle all exceptions. Turn off to let debugging middleware handle exceptions.

add_hook(name, func)[source]

Attach a callback to a hook. Three hooks are currently implemented:

before_request

Executed once before each request. The request context is available, but no routing has happened yet.

after_request

Executed once after each request regardless of its outcome.

app_reset

Called whenever Bottle.reset() is called.

add_route(route)[source]

Add a route object, but do not change the Route.app attribute.

catchall

If true, most exceptions are caught and returned as HTTPError

close()[source]

Close the application and all installed plugins.

config

A ConfigDict for app specific configuration.

delete(path=None, method='DELETE', **options)[source]

Equals route() with a DELETE method parameter.

error(code=500)[source]

Decorator: Register an output handler for a HTTP error code

get(path=None, method='GET', **options)[source]

Equals route().

get_url(routename, **kargs)[source]

Return a string that matches a named route

hook(name)[source]

Return a decorator that attaches a callback to a hook. See add_hook() for details.

install(plugin)[source]

Add a plugin to the list of plugins and prepare it for being applied to all routes of this application. A plugin may be a simple decorator or an object that implements the Plugin API.

match(environ)[source]

Search for a matching route and return a (Route , urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise HTTPError (404/405) on a non-match.

merge(routes)[source]

Merge the routes of another Bottle application or a list of Route objects into this application. The routes keep their ‘owner’, meaning that the Route.app attribute is not changed.

mount(prefix, app, **options)[source]

Mount an application (Bottle or plain WSGI) to a specific URL prefix. Example:

root_app.mount('/admin/', admin_app)
Parameters:
  • prefix – path prefix or mount-point. If it ends in a slash, that slash is mandatory.

  • app – an instance of Bottle or a WSGI application.

All other parameters are passed to the underlying route() call.

post(path=None, method='POST', **options)[source]

Equals route() with a POST method parameter.

put(path=None, method='PUT', **options)[source]

Equals route() with a PUT method parameter.

remove_hook(name, func)[source]

Remove a callback from a hook.

reset(route=None)[source]

Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected.

resources

A ResourceManager for application files

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. See Router 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) equals route(...)(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()).

run(**kwargs)[source]

Calls run() with the same parameters.

trigger_hook(_Bottle__name, *args, **kwargs)[source]

Trigger a hook and return a list of results.

uninstall(plugin)[source]

Uninstall plugins. Pass an instance to remove a specific plugin, a type object to remove all plugins that match that type, a string to remove all plugins with a matching name attribute or True to remove all plugins. Return the list of removed plugins.

wsgi(environ, start_response)[source]

The bottle WSGI-interface.

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.

bottle.Request

alias of BaseRequest

bottle.Response

alias of BaseResponse

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 bottle.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 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).

classmethod search(name, lookup=[])[source]

Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.

bottle.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.

bottle.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