bottle – API Reference

Platforms: Unix, Windows

This is an API reference, NOT a documentation.

bottle.debug(mode=True)
Change the debug level. There is only one debug level supported at the moment.
bottle.url(routename, **kargs)
Return a string that matches a named route
bottle.request
Whenever a page is requested, the Bottle WSGI handler stores metadata about the current request into this instance of Request. It is thread-save and can be accessed from within handler functions.
bottle.response
The Bottle WSGI handler uses metasata assigned to this instance of Response to generate the WSGI response.
bottle.HTTP_CODES
A dict of known HTTP error and status codes
bottle.app()
Return the current default Bottle instance. This is used by many module level functions and decorators such as route() and debug(). Actually, app is a AppStack instance and supports methods like AppStack.push() and AppStack.pop()

These decorators are shortcuts for their counterparts in Bottle

bottle.route(*a, **ka)

Decorator: Bind a route to a callback. The method parameter (default: GET) specifies the HTTP request method to listen to

The shortcuts get(), post(), put(), delete() have different defaults fot the method attribute.

The Bottle Class

class bottle.Bottle(catchall=True, autojson=True, path='')

WSGI application

add_filter(ftype, func)
Register a new output filter. Whenever bottle hits a handler output matching ftype, func is applyed to it.
error(code=500)
Decorator: Registrer an output handler for a HTTP error code
get_url(routename, **kargs)
Return a string that matches a named route
handle(url, method, catchall=True)
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 (None, {}). method: HEAD falls back to GET. HEAD and GET fall back to ALL.
mount(app, script_path)
Mount a Bottle application to a specific URL prefix
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 path. See yieldroutes() for details.

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

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 save to use the global instance in multi-threaded environments too.

class bottle.Request(environ=None, app=None)

Represents a single HTTP request using thread-local attributes. The Resquest object wrapps 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

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

Bind a new WSGI enviroment and clear out all previously computed attributes.

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

keys()
Shortcut for Request.environ.keys()
params
A combined MultiDict with POST and GET parameters.
path_shift(count=1)
Shift some levels of PATH_INFO into SCRIPT_NAME and return the moved part. count defaults to 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 bottle.Response

Represents a single HTTP response using thread-local attributes.

COOKIES
A dict-like SimpleCookie instance. Use Response.set_cookie() instead.
bind(app)
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.
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.

Data Structures

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

A stack implementation.

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

Exceptions

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

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')

Base class and minimal API for template adapters

__init__(source=None, name=None, lookup=[], encoding='utf8')
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 either self.source or self.filename is set. Both are strings. The lookup-argument works similar to sys.path for templates. The encoding parameter is used to decode byte strings or files.
prepare()
Run preparatios (parsing, caching, ...). It should be possible to call this again to refresh a template.
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 save!
classmethod search(name, lookup=[])
Search name in all directiries specified in lookup. First without, then with common extentions. Return first hit.
bottle.view(tpl_name, **defaults)
Decorator: Rendes a template for a handler. Return a dict of template vars to fill out the template.
bottle.template(tpl, template_adapter=<class 'bottle.SimpleTemplate'>, **args)
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 Simple Template 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

Table Of Contents

Previous topic

Tutorial

Next topic

Simple Template Engine

This Page