API Reference

Bottle prides itself on having source code that is easy to read and follow, so most questions about APIs or inner workings can be answered quickly by inspecting sources. Your IDE should give you the same information you’ll find on this page, as most of it is auto-generates from docstrings and method signatures anyway. If you are new to bottle, you may find theUser’s Guide more helpful as a starting point.

Global functions

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

app()
default_app()

Return the currentStructuring Applications. This is actually a callable instances ofAppStack.

debug(mode=True)[source]

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

install(self,plugin)

Add a plugin to the list of plugins and prepare it for beingapplied to all routes of this application. A plugin may be a simpledecorator or an object that implements thePlugin API.

uninstall(self,plugin)

Uninstall plugins. Pass an instance to remove a specific plugin, a typeobject to remove all plugins that match that type, a string to removeall plugins with a matchingname attribute orTrue to remove allplugins. Return the list of removed plugins.

run(app=None,server='wsgiref',host='127.0.0.1',port=8080,interval=1,reloader=False,quiet=False,plugins=None,debug=None,config=None,**kargs)[source]

Start a server instance. This method blocks until the server terminates.

Parameters:
  • app – WSGI application or target string supported byload_app(). (default:default_app())

  • server – Server adapter to use. Seeserver_names keysfor valid names or pass aServerAdapter subclass.(default:wsgiref)

  • host – Server address to bind to. Pass0.0.0.0 to listens onall interfaces including the external one. (default: 127.0.0.1)

  • port – Server port to bind to. Values below 1024 require rootprivileges. (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.

Global decorators

Bottle maintains a stack ofBottle instances (seeapp() andAppStack)and uses the top of the stack as aStructuring Applications for some of the module-level functionsand decorators. All of those have a corresponding method on theBottle class.

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

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

error(...)

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

hook(self,name)

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

Request Context

The globalrequest andresponse instances are only valid from within an request handler function and represent thecurrent HTTP request or response.

request=<LocalRequest:GEThttp://127.0.0.1/>

A thread-safe instance ofLocalRequest. If accessed from within arequest callback, this instance always refers to thecurrent request(even on a multi-threaded server).

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

A thread-safe instance ofLocalResponse. It is used to change theHTTP response for thecurrent request.

Helper Functions

abort(code=500,text='UnknownError.')[source]

Aborts execution and causes a HTTP error.

redirect(url,code=None)[source]

Aborts execution and causes a 303 or 302 redirect, depending onthe HTTP protocol version.

static_file(filename,root,mimetype=True,download=False,charset='UTF-8',etag=None,headers=None)[source]

Open a file in a safe way and return an instance ofHTTPResponsethat can be sent back to the client.

Parameters:
  • filename – Name or path of the file to send, relative toroot.

  • root – Root path for file lookups. Should be an absolute directorypath.

  • mimetype – Provide the content-type header (default: guess fromfile extension)

  • download – If True, ask the browser to open aSave as… dialoginstead of opening the file with the associated program. You canspecify a custom filename as a string. If not specified, theoriginal filename is used (default: False).

  • charset – The charset for files with atext/* mime-type.(default: UTF-8)

  • etag – Provide a pre-computed ETag header. If set toFalse,ETag handling is disabled. (default: auto-generate ETag header)

  • headers – Additional headers dict to add to the response.

While checking user input is always a good idea, this function providesadditional protection against maliciousfilename parameters frombreaking out of theroot directory and leaking sensitive informationto an attacker.

Read-protected files or files outside of theroot directory areanswered with403AccessDenied. Missing files result in a404NotFound response. Conditional requests (If-Modified-Since,If-None-Match) are answered with304NotModified wheneverpossible.HEAD andRange requests (used by download managers tocheck or continue partial downloads) are also handled automatically.

Exceptions

exceptionBottleException[source]

A base class for exceptions used by bottle.

exceptionHTTPResponse[source]

A subclass ofResponse that can be raised or returned from requesthandlers to short-curcuit request processing and override changes made to theglobalrequest object. This bypasses error handlers, even if the statuscode indicates an error. Return or raiseHTTPError to trigger errorhandlers.

__init__(body='',status=None,headers=None,**more_headers)[source]

Create a new response object.

Parameters:
  • body – The response body as one of the supported types.

  • status – Either an HTTP status code (e.g. 200) or a status lineincluding the reason phrase (e.g. ‘200 OK’).

  • headers – A dictionary or a list of name-value pairs.

Additional keyword arguments are added to the list of headers.Underscores in the header name are replaced with dashes.

apply(other)[source]

Copy the state of this response to a differentResponse object.

exceptionHTTPError[source]

A subclass ofHTTPResponse that triggers error handlers.

__init__(status=None,body=None,exception=None,traceback=None,**more_headers)[source]

Create a new response object.

Parameters:
  • body – The response body as one of the supported types.

  • status – Either an HTTP status code (e.g. 200) or a status lineincluding the reason phrase (e.g. ‘200 OK’).

  • headers – A dictionary or a list of name-value pairs.

Additional keyword arguments are added to the list of headers.Underscores in the header name are replaced with dashes.

TheBottle Class

classBottle[source]

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

Parameters:

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

__init__(**kwargs)[source]
config

AConfigDict for app specific configuration.

resources

AResourceManager for application files

catchall

If true, most exceptions are caught and returned asHTTPError

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 isavailable, but no routing has happened yet.

after_request

Executed once after each request regardless of its outcome.

app_reset

Called wheneverBottle.reset() is called.

remove_hook(name,func)[source]

Remove a callback from a hook.

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

Trigger a hook and return a list of results.

hook(name)[source]

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

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

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

parent_app.mount('/prefix/',child_app)
Parameters:
  • prefix – path prefix ormount-point.

  • app – an instance ofBottle or a WSGI application.

Plugins from the parent application are not applied to the routesof the mounted child application. If you need plugins in the childapplication, install them separately.

While it is possible to use path wildcards within the prefix path(Bottle childs only), it is highly discouraged.

The prefix path must end with a slash. If you want to access theroot of the child application via/prefix in addition to/prefix/, consider adding a route with a 307 redirect to theparent application.

merge(routes)[source]

Merge the routes of anotherBottle application or a list ofRoute objects into this application. The routes keep their‘owner’, meaning that theRoute.app attribute is notchanged.

install(plugin)[source]

Add a plugin to the list of plugins and prepare it for beingapplied to all routes of this application. A plugin may be a simpledecorator or an object that implements thePlugin API.

uninstall(plugin)[source]

Uninstall plugins. Pass an instance to remove a specific plugin, a typeobject to remove all plugins that match that type, a string to removeall plugins with a matchingname attribute orTrue to remove allplugins. Return the list of removed plugins.

reset(route=None)[source]

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

close()[source]

Close the application and all installed plugins.

run(**kwargs)[source]

Callsrun() with the same parameters.

match(environ)[source]

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

get_url(routename,**kargs)[source]

Return a string that matches a named route

add_route(route)[source]

Add a route object, but do not change theRoute.appattribute.

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>')defhello(name):return'Hello%s'%name

The<name> part is a wildcard. SeeRouter for syntaxdetails.

Parameters:
  • path – Request path or a list of paths to listen to. If nopath is specified, it is automatically generated from thesignature of the function.

  • method – HTTP method (GET,POST,PUT, …) or a list ofmethods to listen to. (default:GET)

  • callback – An optional shortcut to avoid the decoratorsyntax.route(...,callback=func) equalsroute(...)(func)

  • name – The name for this route. (default: None)

  • apply – A decorator or plugin or a list of plugins. These areapplied to the route callback in addition to installed plugins.

  • skip – A list of plugins, plugin classes or names. Matchingplugins are not installed to this route.True skips all.

Any additional keyword arguments are stored as route-specificconfiguration and passed to plugins (seePlugin.apply()).

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

Equalsroute().

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

Equalsroute() with aPOST method parameter.

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

Equalsroute() with aPUT method parameter.

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

Equalsroute() with aDELETE method parameter.

patch(path=None,method='PATCH',**options)[source]

Equalsroute() with aPATCH method parameter.

error(code=500,callback=None)[source]

Register an output handler for a HTTP error code. Canbe used as a decorator or called directly

deferror_handler_500(error):return'error_handler_500'app.error(code=500,callback=error_handler_500)@app.error(404)deferror_handler_404(error):return'error_handler_404'
wsgi(environ,start_response)[source]

The bottle WSGI-interface.

TheRequest Object

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

Request

alias ofBaseRequest

classBaseRequest[source]

A wrapper for WSGI environment dictionaries that adds a lot ofconvenient access methods and properties. Most of them are read-only.

Adding new attributes to a request actually adds them to the environdictionary (as ‘bottle.request.ext.<name>’). This is the recommendedway to store and access request-specific data.

MEMFILE_MAX=102400

Maximum size of memory buffer forbody in bytes.

__init__(environ=None)[source]

Wrap a WSGI environ dictionary.

environ

The wrapped WSGI environ dictionary. This is the only real attribute.All other attributes actually are read-only properties.

app[source]

Bottle application handling this request.

route[source]

The bottleRoute object that matches this request.

url_args[source]

The arguments extracted from the URL.

propertypath

The value ofPATH_INFO with exactly one prefixed slash (to fixbroken clients and avoid the “empty path” edge case).

propertymethod

TheREQUEST_METHOD value as an uppercase string.

headers[source]

AWSGIHeaderDict that provides case-insensitive access toHTTP request headers.

get_header(name,default=None)[source]

Return the value of a request header, or a given default value.

cookies[source]

Cookies parsed into aFormsDict. Signed cookies are NOTdecoded. Useget_cookie() if you expect signed cookies.

get_cookie(key,default=None,secret=None,digestmod=<built-infunctionopenssl_sha256>)[source]

Return the content of a cookie. To read aSigned Cookie, thesecret must match the one used to create the cookie (seeResponse.set_cookie). If anything goes wrong (missingcookie or wrong signature), return a default value.

query[source]

Thequery_string parsed into aFormsDict. Thesevalues are sometimes called “URL arguments” or “GET parameters”, butnot to be confused with “URL wildcards” as they are provided by theRouter.

forms[source]

Form values parsed from anurl-encoded ormultipart/form-dataencoded POST or PUT request body. The result is returned as aFormsDict. All keys and values are strings. File uploadsare stored separately infiles.

params[source]

AFormsDict with the combined values ofquery andforms. File uploads are stored infiles.

files[source]

File uploads parsed frommultipart/form-data encoded POST or PUTrequest body. The values are instances ofFileUpload.

json[source]

If theContent-Type header isapplication/json orapplication/json-rpc, this property holds the parsed contentof the request body. Only requests smaller thanMEMFILE_MAXare processed to avoid memory exhaustion.Invalid JSON raises a 400 error response.

propertybody

The HTTP request body as a seek-able file-like object. Depending onMEMFILE_MAX, this is either a temporary file or aio.BytesIO instance. Accessing this property for the firsttime reads and replaces thewsgi.input environ variable.Subsequent accesses just do aseek(0) on the file object.

propertychunked

True if Chunked transfer encoding was.

GET

An alias forquery.

POST[source]

The values offorms andfiles combined into a singleFormsDict. Values are either strings (form values) orinstances ofFileUpload.

propertyurl

The full request URI including hostname and scheme. If your applives behind a reverse proxy or load balancer and you get confusingresults, make sure that theX-Forwarded-Host header is setcorrectly.

urlparts[source]

Theurl string as anurlparse.SplitResult tuple.The tuple contains (scheme, host, path, query_string and fragment),but the fragment is always empty because it is not visible to theserver.

propertyfullpath

Request path includingscript_name (if present).

propertyquery_string

The rawquery part of the URL (everything in between?and#) as a string.

propertyscript_name

The initial portion of the URL’spath that was removed by a higherlevel (server or routing middleware) before the application wascalled. This script path is returned with leading and tailingslashes.

path_shift(shift=1)[source]
Shift path segments frompath toscript_name and

vice versa.

Parameters:

shift – The number of path segments to shift. May be negativeto change the shift direction. (default: 1)

propertycontent_length

The request body length as an integer. The client is responsible toset this header. Otherwise, the real length of the body is unknownand -1 is returned. In this case,body will be empty.

propertycontent_type

The Content-Type header as a lowercase-string (default: empty).

propertyis_xhr

True if the request was triggered by a XMLHttpRequest. This onlyworks with JavaScript libraries that support theX-Requested-Withheader (most of the popular libraries do).

propertyis_ajax

Alias foris_xhr. “Ajax” is not the right term.

propertyauth

HTTP authentication data as a (user, password) tuple. Thisimplementation currently supports basic (not digest) authenticationonly. If the authentication happened at a higher level (e.g. in thefront web-server or a middleware), the password field is None, butthe user field is looked up from theREMOTE_USER environvariable. On any errors, None is returned.

propertyremote_route

A list of all IPs that were involved in this request, starting withthe client IP and followed by zero or more proxies. This does onlywork if all proxies support the`X-Forwarded-For header. Notethat this information can be forged by malicious clients.

propertyremote_addr

The client IP as a string. Note that this information can be forgedby malicious clients.

copy()[source]

Return a newRequest with a shallowenviron copy.

__setattr__(name,value)[source]

Define new attributes that are local to the bound request environment.

classLocalRequest[source]

A thread-local subclass ofBaseRequest with a differentset of attributes for each thread. There is usually only one globalinstance of this class (request). If accessed during arequest/response cycle, this instance always refers to thecurrentrequest (even on a multithreaded server).

bind(environ=None)

Wrap a WSGI environ dictionary.

environ

The wrapped WSGI environ dictionary. This is the only real attribute.All other attributes actually are read-only properties.

TheResponse Object

TheResponse class stores the HTTP status code as well as headers and cookies that are to be sent to the client. Similar tobottle.request there is a thread-localbottle.response instance that can be used to adjust thecurrent response. Moreover, you can instantiateResponse and return it from your request handler. In this case, the custom instance overrules the headers and cookies defined in the global one.

Response

alias ofBaseResponse

classBaseResponse[source]

Storage class for a response body as well as headers and cookies.

This class does support dict-like case-insensitive item-access toheaders, but is NOT a dict. Most notably, iterating over a responseyields parts of the body and not the headers.

__init__(body='',status=None,headers=None,**more_headers)[source]

Create a new response object.

Parameters:
  • body – The response body as one of the supported types.

  • status – Either an HTTP status code (e.g. 200) or a status lineincluding the reason phrase (e.g. ‘200 OK’).

  • headers – A dictionary or a list of name-value pairs.

Additional keyword arguments are added to the list of headers.Underscores in the header name are replaced with dashes.

copy(cls=None)[source]

Returns a copy of self.

propertystatus_line

The HTTP status line as a string (e.g.404NotFound).

propertystatus_code

The HTTP status code as an integer (e.g. 404).

propertystatus

A writeable property to change the HTTP response status. It acceptseither a numeric code (100-999) or a string with a custom reasonphrase (e.g. “404 Brain not found”). Bothstatus_line andstatus_code are updated accordingly. The return value isalways a status string.

propertyheaders

An instance ofHeaderDict, a case-insensitive dict-likeview on the response headers.

get_header(name,default=None)[source]

Return the value of a previously defined header. If there is noheader with that name, return a default value.

set_header(name,value)[source]

Create a new response header, replacing any previously definedheaders with the same name.

add_header(name,value)[source]

Add an additional response header, not removing duplicates.

iter_headers()[source]

Yield (header, value) tuples, skipping headers that are notallowed with the current response status code.

propertyheaderlist

WSGI conform list of (header, value) tuples.

content_type

Current value of the ‘Content-Type’ header.

content_length

Current value of the ‘Content-Length’ header.

expires

Current value of the ‘Expires’ header.

propertycharset

Return the charset specified in the content-type header (default: utf8).

set_cookie(name,value,secret=None,digestmod=<built-infunctionopenssl_sha256>,**options)[source]

Create a new cookie or replace an old one. If thesecret parameter isset, create aSigned Cookie (described below).

Parameters:
  • name – the name of the cookie.

  • value – the value of the cookie.

  • secret – a signature key required for signed cookies.

Additionally, this method accepts all RFC 2109 attributes that aresupported bycookie.Morsel, including:

Parameters:
  • maxage – maximum age in seconds. (default: None)

  • expires – a datetime object or UNIX timestamp. (default: None)

  • domain – the domain that is allowed to read the cookie.(default: current domain)

  • path – limits the cookie to a given path (default: current path)

  • secure – limit the cookie to HTTPS connections (default: off).

  • httponly – prevents client-side javascript to read this cookie(default: off, requires Python 2.6 or newer).

  • samesite – Control or disable third-party use for this cookie.Possible values:lax,strict ornone (default).

If neitherexpires normaxage is set (default), the cookie willexpire at the end of the browser session (as soon as the browserwindow is closed).

Signed cookies may store any pickle-able object and arecryptographically signed to prevent manipulation. Keep in mind thatcookies are limited to 4kb in most browsers.

Warning: Pickle is a potentially dangerous format. If an attackergains access to the secret key, he could forge cookies that executecode on server side if unpickled. Using pickle is discouraged andsupport for it will be removed in later versions of bottle.

Warning: Signed cookies are not encrypted (the client can still seethe content) and not copy-protected (the client can restore an oldcookie). The main intention is to make pickling and unpicklingsave, not to store secret information at client side.

delete_cookie(key,**kwargs)[source]

Delete a cookie. Be sure to use the samedomain andpathsettings as used to create the cookie.

classLocalResponse[source]

A thread-local subclass ofBaseResponse with a differentset of attributes for each thread. There is usually only one globalinstance of this class (response). Its attributes are usedto build the HTTP response at the end of the request/response cycle.

bind(body='',status=None,headers=None,**more_headers)

Create a new response object.

Parameters:
  • body – The response body as one of the supported types.

  • status – Either an HTTP status code (e.g. 200) or a status lineincluding the reason phrase (e.g. ‘200 OK’).

  • headers – A dictionary or a list of name-value pairs.

Additional keyword arguments are added to the list of headers.Underscores in the header name are replaced with dashes.

propertybody

Thread-local property

Data Structures

classAppStack[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 newBottle instance to the stack

new_app(value=None)

Add a newBottle instance to the stack

classConfigDict[source]

A dict-like configuration storage with additional support fornamespaces, validators, meta-data and overlays.

This dict-like class is heavily optimized for read access.Read-only methods and item access should be as fast as a native dict.

__init__()[source]
load_module(name,squash=True)[source]

Load values from a Python module.

Import a python module by name and add all upper-case module-levelvariables to this config dict.

Parameters:
  • name – Module name to import and load.

  • squash – If true (default), nested dicts are assumed torepresent namespaces and flattened (seeload_dict()).

load_config(filename,**options)[source]

Load values from*.ini style config files using configparser.

INI style sections (e.g.[section]) are used as namespace forall keys within that section. Both section and key names may containdots as namespace separators and are converted to lower-case.

The special sections[bottle] and[ROOT] refer to the rootnamespace and the[DEFAULT] section defines default values for allother sections.

Parameters:
  • filename – The path of a config file, or a list of paths.

  • options – All keyword parameters are passed to the underlyingconfigparser.ConfigParser constructor call.

load_dict(source,namespace='')[source]

Load values from a dictionary structure. Nesting can be used torepresent namespaces.

>>>c=ConfigDict()>>>c.load_dict({'some':{'namespace':{'key':'value'}}}){'some.namespace.key': 'value'}
update(*a,**ka)[source]

If the first parameter is a string, all keys are prefixed with thisnamespace. Apart from that it works just as the usual dict.update().

>>>c=ConfigDict()>>>c.update('some.namespace',key='value')
setdefault(key,value=None)[source]

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

meta_get(key,metafield,default=None)[source]

Return the value of a meta field for a key.

meta_set(key,metafield,value)[source]

Set the meta field for a key to a new value.

Meta-fields are shared between all members of an overlay tree.

meta_list(key)[source]

Return an iterable of meta field names defined for a key.

classMultiDict[source]

This dict stores multiple values per key, but behaves exactly like anormal 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.

__init__(*a,**k)[source]
keys()aset-likeobjectprovidingaviewonD'skeys[source]
values()anobjectprovidingaviewonD'svalues[source]
items()aset-likeobjectprovidingaviewonD'sitems[source]
iterkeys()

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

itervalues()

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

iteritems()

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

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 notpresent or the type conversion fails.

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

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

append(key,value)[source]

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

replace(key,value)[source]

Replace the list of values with a single value.

getall(key)[source]

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)

getlist(key)

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

classWSGIHeaderDict[source]

This dict-like class wraps a WSGI environ dict and provides convenientaccess to HTTP_* fields. Header names are case-insensitive and titled by default.

cgikeys=('CONTENT_TYPE','CONTENT_LENGTH')

List of keys that do not have aHTTP_ prefix.

__init__(environ)[source]
raw(key,default=None)[source]

Return the header value as is (not utf8-translated).

keys()aset-likeobjectprovidingaviewonD'skeys[source]
classHeaderDict[source]

A case-insensitive version ofMultiDict that defaults toreplace the old value instead of appending it.

__init__(*a,**ka)[source]
append(key,value)[source]

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

replace(key,value)[source]

Replace the list of values with a single value.

getall(key)[source]

Return a (possibly empty) list of values for a 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 notpresent or the type conversion fails.

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

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

classFormsDict[source]

ThisMultiDict subclass is used to store request form data.Additionally to the normal dict-like item access methods, this containeralso supports attribute-like access to its values. Missing attributesdefault to an empty string.

Changed in version 0.14:All keys and values are now decoded as utf8 by default, item andattribute access will return the same string.

decode(encoding=None)[source]

(deprecated) Starting with 0.13 all keys and values are alreadycorrectly decoded.

getunicode(name,default=None,encoding=None)[source]

(deprecated) Return the value as a unicode string, or the default.

classFileUpload[source]
__init__(fileobj,name,filename,headers=None)[source]

Wrapper for a single file uploaded viamultipart/form-data.

file

Open file(-like) object (BytesIO buffer or temporary file)

name

Name of the upload form field

raw_filename

Raw filename as sent by the client (may contain unsafe characters)

headers

AHeaderDict with additional headers (e.g. content-type)

content_type

Current value of the ‘Content-Type’ header.

content_length

Current value of the ‘Content-Length’ header.

get_header(name,default=None)[source]

Return the value of a header within the multipart part.

filename()[source]

Name of the file on the client file system, but normalized to ensurefile system compatibility. An empty filename is returned as ‘empty’.

Only ASCII letters, digits, dashes, underscores and dots areallowed in the final filename. Accents are removed, if possible.Whitespace is replaced by a single dash. Leading or tailing dotsor dashes are removed. The filename is limited to 255 characters.

save(destination,overwrite=False,chunk_size=65536)[source]

Save file to disk or copy its content to an open file(-like) object.Ifdestination is a directory,filename is added to thepath. Existing files are not overwritten by default (IOError).

Parameters:
  • destination – File path, directory or file(-like) object.

  • overwrite – If True, replace existing files. (default: False)

  • chunk_size – Bytes to read at a time. (default: 64kb)

Request routing

classRouter[source]

A Router is an ordered collection of route->target pairs. It is used toefficiently match WSGI requests against a number of routes and returnthe first target that satisfies the request. The target may be anything,usually a string, ID or callable object. A route consists of a path-ruleand a HTTP method.

The path-rule is either a static path (e.g./contact) or a dynamicpath that contains wildcards (e.g./wiki/<page>). The wildcard syntaxand details on the matching order are described in docs:routing.

__init__(strict=False)[source]
strict_order

If true, static routes are no longer checked first.

add_filter(name,func)[source]

Add a filter. The provided function is called with the configurationstring as parameter and must return a (regexp, to_python, to_url) tuple.The first element is a string, the last two are callables or None.

add(rule,method,target,name=None)[source]

Add a new rule or replace the target for an existing rule.

build(_name,*anons,**query)[source]

Build an URL by filling the wildcards in a rule.

match(environ)[source]

Return a (target, url_args) tuple or raise HTTPError(400/404/405).

classRoute[source]

This class wraps a route callback along with route specific metadata andconfiguration and applies Plugins on demand. It is also responsible forturning an URL path rule into a regular expression usable by the Router.

__init__(app,rule,method,callback,name=None,plugins=None,skiplist=None,**config)[source]
app

The application this route is installed to.

rule

The path-rule string (e.g./wiki/<page>).

method

The HTTP method as a string (e.g.GET).

callback

The original callback with no plugins applied. Useful for introspection.

name

The name of the route (if specified) orNone.

plugins

A list of route-specific plugins (seeBottle.route()).

skiplist

A list of plugins to not apply to this route (seeBottle.route()).

config

Additional keyword arguments passed to theBottle.route()decorator are stored in this dictionary. Used for route-specificplugin configuration and meta-data.

call()[source]

The route callback with all plugins applied. This property iscreated on demand and then cached to speed up subsequent requests.

reset()[source]

Forget any cached values. The next timecall is accessed,all plugins are re-applied.

prepare()[source]

Do all on-demand work immediately (useful for debugging).

all_plugins()[source]

Yield all Plugins affecting this route.

get_undecorated_callback()[source]

Return the callback. If the callback is a decorated function, try torecover the original function.

get_callback_args()[source]

Return a list of argument names the callback (most likely) acceptsas keyword arguments. If the callback is a decorated function, tryto recover the original function before inspection.

get_config(key,default=None)[source]

Lookup a config field and return its value, first checking theroute.config, then route.app.config.

Templating

All template engines supported bybottle implement theBaseTemplate API. This way it is possible to switch and mix template engines without changing the application code at all.

classBaseTemplate[source]

Base class and minimal API for template adapters

__init__(source=None,name=None,lookup=None,encoding='utf8',**settings)[source]

Create a new template.If the source parameter (str or buffer) is missing, the name argumentis used to guess a template filename. Subclasses can assume thatself.source and/or self.filename are set. Both are strings.The lookup, encoding and settings parameters are stored as instancevariables.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.

classmethodsearch(name,lookup=None)[source]

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

classmethodglobal_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 toupdate settings.

render(*args,**kwargs)[source]

Render the template with the specified local variables and returna single byte or unicode string. If it is a byte string, the encodingmust 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 notprocess 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 dictionariesor directly (as keyword arguments).

TEMPLATE_PATH=['./','./views/']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list.The argument must be an iterable if specified.

Global search path for templates.

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

view()

template()

MakoTemplate

http://www.makotemplates.org

mako_view()

mako_template()

CheetahTemplate

http://www.cheetahtemplate.org/

cheetah_view()

cheetah_template()

Jinja2Template

https://jinja.palletsprojects.com/

jinja2_view()

jinja2_template()

To useMakoTemplate as your default template engine, just import its specialised decorator and render function:

frombottleimportmako_viewasview,mako_templateastemplate

HTTP utilities

parse_date(ims)[source]

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

parse_auth(header)[source]

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

cookie_encode(data,key,digestmod=None)[source]

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

cookie_decode(data,key,digestmod=None)[source]

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

cookie_is_encoded(data)[source]

Return True if the argument looks like a encoded cookie.

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

HTTP_CODES

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

Misc utilities

classDictProperty[source]

Property that maps to a key in a local dict-like attribute.

__init__(attr,key=None,read_only=False)[source]
classmethod__new__(*args,**kwargs)
classcached_property[source]

A property that is only computed once per instance and then replacesitself with an ordinary attribute. Deleting the attribute resets theproperty.

__init__(func)[source]
classmethod__new__(*args,**kwargs)
classlazy_attribute[source]

A property that caches itself to the class object.

__init__(func)[source]
classmethod__new__(*args,**kwargs)
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 functiontakes 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>'
load(target,**namespace)[source]

Import a module or fetch an object from a module.

  • package.module returnsmodule as a module object.

  • pack.mod:name returns the module variablename frompack.mod.

  • pack.mod:func() callspack.mod.func() and returns the result.

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

load_app(target)[source]

Load a bottle application from a module and make sure that the importdoes not affect the current default application, but returns a separateapplication object. Seeload() for the target parameter.