API Reference

Platforms: Unix, Windows

This is an API reference, NOT documentation. If you are new to bottle, have a look at the Tutorial.

Module Contents

The module defines several functions, constants, and an exception.

app()
Return the current default application (see Bottle). Actually, this is a callable instance of AppStack and implements a stack-like API.
debug(mode=True)
Change the debug level. There is only one debug level supported at the moment.
request
Whenever a page is requested, the Bottle WSGI handler stores metadata about the current request into this instance of Request. It is thread-safe and can be accessed from within handler functions.
response
The Bottle WSGI handler uses metadata assigned to this instance of Response to generate the WSGI response.
HTTP_CODES
A dict of known HTTP error and status codes

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', name=None)
Decorator to bind a function to a path. This equals Bottle.route() using the current default application.
get(...)
post(...)
put(...)
delete(...)
These are equal to route() with the method parameter set to the corresponding verb.
error(...)
Calls Bottle.error() using the default application.
url(...)
Calls Bottle.url() using the default application.

WSGI and HTTP Utilities

parse_date(ims)
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
parse_auth(header)
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
cookie_encode(data, key)
Encode and sign a pickle-able object. Return a string
cookie_decode(data, key)
Verify and decode an encoded string. Return an object or None
cookie_is_encoded(data)
Return True if the argument looks like a encoded cookie.
yieldroutes(func)

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)

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 ths shift direction. (default: 1)

Data Structures

class MultiDict(*a, **k)
A dict that remembers old values for each key
class HeaderDict(*a, **k)
Same as MultiDict, but title()s the keys and overwrites by default.
class AppStack

A stack implementation.

push(value=None)
Add a new Bottle instance to the stack

Exceptions

exception BottleException
A base class for exceptions used by bottle.
exception HTTPResponse(output='', status=200, header=None)
Used to break execution and immediately finish the response
exception HTTPError(code=500, output='Unknown Error', exception=None, traceback=None, header=None)
Used to generate an error page

The Bottle Class

class Bottle(catchall=True, autojson=True, config=None)

WSGI application

add_filter(ftype, func)
Register a new output filter. Whenever bottle hits a handler output matching ftype, func is applied to it.
delete(path=None, method='DELETE', **kargs)
Decorator: Bind a function to a DELETE request path. See :meth:’route’ for details.
error(code=500)
Decorator: Registrer an output handler for a HTTP error code
get(path=None, method='GET', **kargs)
Decorator: Bind a function to a GET request path. See :meth:’route’ for details.
get_url(routename, **kargs)
Return a string that matches a named route
handle(url, method)
Execute the handler bound to the specified url and method and return its output. If catchall is true, exceptions are catched and returned as HTTPError(500) objects.
match_url(path, method='GET')
Find a callback bound to a path and a specific HTTP method. Return (callback, param) tuple or raise HTTPError. method: HEAD falls back to GET. All methods fall back to ANY.
mount(app, script_path)
Mount a Bottle application to a specific URL prefix
post(path=None, method='POST', **kargs)
Decorator: Bind a function to a POST request path. See :meth:’route’ for details.
put(path=None, method='PUT', **kargs)
Decorator: Bind a function to a PUT request path. See :meth:’route’ for details.
route(path=None, method='GET', **kargs)

Decorator: bind a function to a GET request path.

If the path parameter is None, the signature of the decorated function is used to generate the paths. See yieldroutes() for details.

The method parameter (default: GET) specifies the HTTP request method to listen to. You can specify a list of methods too.

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, config=None)

Represents a single HTTP request using thread-local attributes. The Request object wraps a WSGI environment and can be used as such.

COOKIES

Cookie information parsed into a dictionary.

Secure cookies are NOT decoded automatically. See Request.get_cookie() for details.

GET

The QUERY_STRING parsed into a MultiDict.

Keys and values are strings. Multiple values per key are possible. See MultiDict for details.

POST

Property: The HTTP POST body parsed into a MultiDict.

This supports urlencoded and multipart POST requests. Multipart is commonly used for file uploads and may result in some of the values being cgi.FieldStorage objects instead of strings.

Multiple values per key are possible. See MultiDict for details.

auth

HTTP authorisation data as a (user, passwd) tuple. (experimental)

This implementation currently only supports basic auth and returns None on errors.

bind(environ, config=None)

Bind a new WSGI enviroment.

This is done automatically for the global bottle.request instance on every request.

body

The HTTP request body as a seekable buffer object.

This property returns a copy of the wsgi.input stream and should be used instead of environ[‘wsgi.input’].

content_length
Content-Length header as an integer, -1 if not specified
copy()
Returns a copy of self
files
Property: HTTP POST file uploads parsed into a MultiDict.
forms
Property: HTTP POST form data parsed into a MultiDict.
fullpath
Request path including SCRIPT_NAME (if present)
Return the (decoded) value of a cookie.
header

HeaderDict filled with request headers.

HeaderDict keys are case insensitive str.title()d

is_ajax
True if the request was generated using XMLHttpRequest
params
A combined MultiDict with POST and GET parameters.
path_shift(shift=1)

Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

Parameter:shift – The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
query_string
The content of the QUERY_STRING environment variable.
url

Full URL as requested by the client (computed).

This value is constructed out of different environment variables and includes scheme, host, port, scriptname, path and query string.

class Response(config=None)

Represents a single HTTP response using thread-local attributes.

COOKIES
A dict-like SimpleCookie instance. Use Response.set_cookie() instead.
bind(config=None)
Resets the Response object to its factory defaults.
charset

Return the charset specified in the content-type header.

This defaults to UTF-8.

content_type
Current ‘Content-Type’ header.
copy()
Returns a copy of self
get_content_type()
Current ‘Content-Type’ header.
headerlist
Returns a wsgi conform list of header/value pairs.

Add a new cookie with various options.

If the cookie value is not a string, a secure cookie is created.

Possible options are:
expires, path, comment, domain, max_age, secure, version, httponly See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details
wsgiheader()
Returns a wsgi conform list of header/value pairs.

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)

Base class and minimal API for template adapters

__init__(source=None, name=None, lookup=[], encoding='utf8', **settings)
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)
This reads or sets the global settings stored in class.settings.
prepare(**options)
Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.
render(**args)
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!
classmethod search(name, lookup=[])
Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
view(tpl_name, **defaults)

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(tpl, template_adapter=<class 'bottle.SimpleTemplate'>, **kwargs)
Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter.

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