module documentation

Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with url parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file and with no dependencies other than the Python Standard Library.

Homepage and documentation: http://bottlepy.org/

Copyright (c) 2016, Marcel Hellkamp. License: MIT (see LICENSE for details)

Class ​App​Stack A stack-like list. Calling it returns the head of the stack.
Class ​Base​Request A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only.
Class ​Base​Response Storage class for a response body as well as headers and cookies.
Class ​Base​Template Base class and minimal API for template adapters
Class ​Bottle Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications.
Class ​Bottle​Exception A base class for exceptions used by bottle.
Class ​Config​Dict A dict-like configuration storage with additional support for namespaces, validators, meta-data, on_change listeners and more.
Class ​File​Upload No class docstring; 1/1 property, 0/4 instance variable, 0/2 class variable, 3/4 methods documented
Class ​Forms​Dict No summary
Class ​Header​Dict A case-insensitive version of MultiDict that defaults to replace the old value instead of appending it.
Class ​HTTPError Undocumented
Class ​HTTPResponse Undocumented
Class ​Local​Request No summary
Class ​Local​Response No summary
Class ​Multi​Dict 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.
Class ​Resource​Manager This class manages a list of search paths and helps to find and open application-bound resources (files).
Class ​Route This class wraps a route callback along with route specific metadata and configuration and applies Plugins on demand. It is also responsible for turing an URL path rule into a regular expression usable by the Router.
Class ​Simple​Template No class docstring; 0/2 property, 0/4 instance variable, 1/5 method documented
Class ​WSGIHeader​Dict No summary
Function cookie​_decode Verify and decode an encoded string. Return an object or None.
Function cookie​_encode Encode and sign a pickle-able object. Return a (byte) string
Function cookie​_is​_encoded Return True if the argument looks like a encoded cookie.
Function debug Change the debug level. There is only one debug level supported at the moment.
Function load Import a module or fetch an object from a module.
Function load​_app 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.
Function parse​_auth Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
Function parse​_date Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
Function path​_shift Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
Function run Start a server instance. This method blocks until the server terminates.
Function template No summary
Function view Decorator: renders a template for a handler. The handler can control its behavior like that:
Function yieldroutes 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:
Constant DEBUG Undocumented
Constant ERROR​_PAGE​_TEMPLATE Undocumented
Constant NORUN Undocumented
Constant TEMPLATE​_PATH Undocumented
Constant TEMPLATES Undocumented
Variable __author__ Undocumented
Variable __license__ Undocumented
Variable __version__ Undocumented
Variable app Undocumented
Variable callable Undocumented
Variable cheetah​_template Undocumented
Variable cheetah​_view Undocumented
Variable default​_app Undocumented
Variable delete Undocumented
Variable error Undocumented
Variable ext Undocumented
Variable get Undocumented
Variable hook Undocumented
Variable install Undocumented
Variable jinja2​_template Undocumented
Variable jinja2​_view Undocumented
Variable json​_loads Undocumented
Variable local Undocumented
Variable mako​_template Undocumented
Variable mako​_view Undocumented
Variable mount Undocumented
Variable post Undocumented
Variable put Undocumented
Variable py25 Undocumented
Variable py31 Undocumented
Variable py3k Undocumented
Variable request Undocumented
Variable response Undocumented
Variable route Undocumented
Variable server​_names Undocumented
Variable tonat Undocumented
Variable uninstall Undocumented
Variable url Undocumented
Variable urlunquote Undocumented
Class ​_closeiter This only exists to be able to attach a .close method to iterators that do not support attribute assignment (most of itertools).
Class _​Import​Redirect No class docstring; 0/3 instance variable, 1/3 method documented
Class ​App​Engine​Server Adapter for Google App Engine.
Class ​Auto​Server Untested.
Class ​Bjoern​Server Fast server written in C: https://github.com/jonashaag/bjoern
Class cached​_property A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property.
Class ​CGIServer Undocumented
Class ​Cheetah​Template Undocumented
Class ​Cherry​Py​Server Undocumented
Class ​Dict​Property Property that maps to a key in a local dict-like attribute.
Class ​Diesel​Server Untested.
Class ​Eventlet​Server Untested
Class ​Fapws​Server Extremely fast webserver using libev. See http://www.fapws.org/
Class ​File​Checker​Thread Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old.
Class ​Flup​FCGIServer Undocumented
Class ​Gevent​Server Untested. Options:
Class ​Gevent​Socket​IOServer Undocumented
Class ​Gunicorn​Server Untested. See http://gunicorn.org/configure.html for options.
Class ​Header​Property Undocumented
Class ​Jinja2​Template Undocumented
Class ​JSONPlugin Undocumented
Class lazy​_attribute A property that caches itself to the class object.
Class ​Mako​Template Undocumented
Class ​Meinheld​Server Undocumented
Class ​NCText​IOWrapper Undocumented
Class ​Paste​Server Undocumented
Class ​Plugin​Error Undocumented
Class ​Rocket​Server Untested.
Class ​Route​Build​Error The route could not be built.
Class ​Route​Error This is a base class for all routing related exceptions
Class ​Router No summary
Class ​Route​Reset If raised by a plugin or request handler, the route is reset and all plugins are re-applied.
Class ​Router​Unknown​Mode​Error Undocumented
Class ​Route​Syntax​Error The route parser found something not supported by this router.
Class ​Server​Adapter Undocumented
Class ​Stpl​Parser Parser for stpl templates.
Class ​Stpl​Syntax​Error Undocumented
Class ​Template​Error Undocumented
Class ​Template​Plugin No summary
Class ​Tornado​Server The super hyped asynchronous server by facebook. Untested.
Class ​Twisted​Server Untested.
Class ​Waitress​Server Undocumented
Class ​WSGIFile​Wrapper Undocumented
Class ​WSGIRef​Server Undocumented
Function ​_e Undocumented
Function ​_file​_iter​_range Yield chunks from a range in a file. No chunk is bigger than maxread.
Function ​_hkey Undocumented
Function ​_hval Undocumented
Function ​_lscmp Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.
Function ​_parse​_qsl Undocumented
Function ​_raise Undocumented
Function ​_re​_flatten Turn all capturing groups in a regular expression pattern into non-capturing groups.
Function abort Aborts execution and causes a HTTP error.
Function auth​_basic Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
Function depr Undocumented
Function html​_escape Escape HTML special characters &<> and quotes '".
Function html​_quote Escape and quote a string to be used as an HTTP attribute.
Function http​_date Undocumented
Function json​_dumps Undocumented
Function local​_property Undocumented
Function make​_default​_app​_wrapper Return a callable that relays calls to the current default app.
Function makelist Undocumented
Function parse​_range​_header Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
Function redirect Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
Function static​_file No summary
Function tob Undocumented
Function touni Undocumented
Function update​_wrapper Undocumented
Constant ​_HTTP​_STATUS​_LINES Undocumented
Variable ​_stderr Undocumented
Variable ​_stdout Undocumented
def cookie_decode(data, key):
Verify and decode an encoded string. Return an object or None.
def cookie_encode(data, key):
Encode and sign a pickle-able object. Return a (byte) string
def cookie_is_encoded(data):
Return True if the argument looks like a encoded cookie.
def debug(mode=True):
Change the debug level. There is only one debug level supported at the moment.
def load(target, **namespace):

Import a module or fetch an object from a module.

  • package.module returns module as a module object.
  • pack.mod:name returns the module variable name from pack.mod.
  • pack.mod:func() calls pack.mod.func() and returns the result.

The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: import_string('re:compile(x)', x='[a-z]')

def load_app(target):
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.
def parse_auth(header):
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
def parse_date(ims):
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
def path_shift(script_name, path_info, shift=1):
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
Parameters
script​_nameThe PATH_INFO path.
path​_infoUndocumented
shiftThe number of path fragments to shift. May be negative to change the shift direction. (default: 1)
Returns
The modified paths.
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs):
Start a server instance. This method blocks until the server terminates.
Parameters
appWSGI application or target string supported by load_app. (default: default_app)
serverServer adapter to use. See server_names keys for valid names or pass a ServerAdapter subclass. (default: wsgiref)
hostServer address to bind to. Pass 0.0.0.0 to listens on all interfaces including the external one. (default: 127.0.0.1)
portServer port to bind to. Values below 1024 require root privileges. (default: 8080)
intervalAuto-reloader interval in seconds (default: 1)
reloaderStart auto-reloading server? (default: False)
quietSuppress output to stdout and stderr? (default: False)
pluginsUndocumented
debugUndocumented
**kargsUndocumented
optionsOptions passed to the server adapter.
def template(*args, **kwargs):
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).
def 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.
def 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>'
DEBUG: bool =

Undocumented

Value
False
ERROR_PAGE_TEMPLATE =

Undocumented

Value
'''
%%try:
    %%from %s import DEBUG, HTTP_CODES, request, touni
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html>
        <head>
            <title>Error: {{e.status}}</title>
...
NORUN: bool =

Undocumented

Value
False
TEMPLATE_PATH: list[str] =

Undocumented

Value
['./', './views/']
TEMPLATES: dict =

Undocumented

Value
{}
__author__: str =

Undocumented

__license__: str =

Undocumented

__version__: str =

Undocumented

app =

Undocumented

callable =

Undocumented

cheetah_template =

Undocumented

cheetah_view =

Undocumented

default_app =

Undocumented

delete =

Undocumented

error =

Undocumented

ext =

Undocumented

get =

Undocumented

hook =

Undocumented

install =

Undocumented

jinja2_template =

Undocumented

jinja2_view =

Undocumented

json_loads =

Undocumented

local =

Undocumented

mako_template =

Undocumented

mako_view =

Undocumented

mount =

Undocumented

post =

Undocumented

put =

Undocumented

py25 =

Undocumented

py31 =

Undocumented

py3k =

Undocumented

request =

Undocumented

response =

Undocumented

route =

Undocumented

server_names =

Undocumented

tonat =

Undocumented

uninstall =

Undocumented

url =

Undocumented

urlunquote =

Undocumented

def _e():

Undocumented

def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
Yield chunks from a range in a file. No chunk is bigger than maxread.
def _hkey(key):

Undocumented

def _hval(value):

Undocumented

def _lscmp(a, b):
Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.
def _parse_qsl(qs):

Undocumented

def _raise(*a):

Undocumented

def _re_flatten(p):
Turn all capturing groups in a regular expression pattern into non-capturing groups.
def abort(code=500, text='Unknown Error.'):
Aborts execution and causes a HTTP error.
def auth_basic(check, realm='private', text='Access denied'):
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
def depr(message, hard=False):

Undocumented

def html_escape(string):
Escape HTML special characters &<> and quotes '".
def html_quote(string):
Escape and quote a string to be used as an HTTP attribute.
def http_date(value):

Undocumented

def json_dumps(data):

Undocumented

def local_property(name=None):

Undocumented

def make_default_app_wrapper(name):
Return a callable that relays calls to the current default app.
def makelist(data):

Undocumented

def parse_range_header(header, maxlen=0):
Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
def redirect(url, code=None):
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
Open a file in a safe way and return HTTPResponse with status code 200, 305, 403 or 404. The Content-Type, Content-Encoding, Content-Length and Last-Modified headers are set if possible. Special support for If-Modified-Since, Range and HEAD requests.
Parameters
filenameName or path of the file to send.
rootRoot path for file lookups. Should be an absolute directory path.
mimetypeDefines the content-type header (default: guess from file extension)
downloadIf True, ask the browser to open a Save as... dialog instead of opening the file with the associated program. You can specify a custom filename as a string. If not specified, the original filename is used (default: False).
charsetThe charset to use for files with a text/* mime-type. (default: UTF-8)
def tob(s, enc='utf8'):

Undocumented

def touni(s, enc='utf8', err='strict'):

Undocumented

def update_wrapper(wrapper, wrapped, *a, **ka):

Undocumented

_HTTP_STATUS_LINES =

Undocumented

Value
dict(((k, '%d %s' % (k, v)) for k, v in HTTP_CODES.items()))
_stderr =

Undocumented

_stdout =

Undocumented