API Reference¶
This is a mostly auto-generated API. If you are new to bottle, you might find the narrative Tutorial more helpful.
Module Contents¶
The module defines several functions, constants, and an exception.
-
debug
(mode=True)[source]¶ Change the debug level. There is only one debug level supported at the moment.
-
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 aServerAdapter
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.
- app – WSGI application or target string supported by
-
load
(target, **namespace)[source]¶ 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]')
-
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.
-
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).
-
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.
-
HTTP_CODES
= {<HTTPStatus.CONTINUE: 100>: 'Continue', <HTTPStatus.SWITCHING_PROTOCOLS: 101>: 'Switching Protocols', <HTTPStatus.PROCESSING: 102>: 'Processing', <HTTPStatus.OK: 200>: 'OK', <HTTPStatus.CREATED: 201>: 'Created', <HTTPStatus.ACCEPTED: 202>: 'Accepted', <HTTPStatus.NON_AUTHORITATIVE_INFORMATION: 203>: 'Non-Authoritative Information', <HTTPStatus.NO_CONTENT: 204>: 'No Content', <HTTPStatus.RESET_CONTENT: 205>: 'Reset Content', <HTTPStatus.PARTIAL_CONTENT: 206>: 'Partial Content', <HTTPStatus.MULTI_STATUS: 207>: 'Multi-Status', <HTTPStatus.ALREADY_REPORTED: 208>: 'Already Reported', <HTTPStatus.IM_USED: 226>: 'IM Used', <HTTPStatus.MULTIPLE_CHOICES: 300>: 'Multiple Choices', <HTTPStatus.MOVED_PERMANENTLY: 301>: 'Moved Permanently', <HTTPStatus.FOUND: 302>: 'Found', <HTTPStatus.SEE_OTHER: 303>: 'See Other', <HTTPStatus.NOT_MODIFIED: 304>: 'Not Modified', <HTTPStatus.USE_PROXY: 305>: 'Use Proxy', <HTTPStatus.TEMPORARY_REDIRECT: 307>: 'Temporary Redirect', <HTTPStatus.PERMANENT_REDIRECT: 308>: 'Permanent Redirect', <HTTPStatus.BAD_REQUEST: 400>: 'Bad Request', <HTTPStatus.UNAUTHORIZED: 401>: 'Unauthorized', <HTTPStatus.PAYMENT_REQUIRED: 402>: 'Payment Required', <HTTPStatus.FORBIDDEN: 403>: 'Forbidden', <HTTPStatus.NOT_FOUND: 404>: 'Not Found', <HTTPStatus.METHOD_NOT_ALLOWED: 405>: 'Method Not Allowed', <HTTPStatus.NOT_ACCEPTABLE: 406>: 'Not Acceptable', <HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: 407>: 'Proxy Authentication Required', <HTTPStatus.REQUEST_TIMEOUT: 408>: 'Request Timeout', <HTTPStatus.CONFLICT: 409>: 'Conflict', <HTTPStatus.GONE: 410>: 'Gone', <HTTPStatus.LENGTH_REQUIRED: 411>: 'Length Required', <HTTPStatus.PRECONDITION_FAILED: 412>: 'Precondition Failed', <HTTPStatus.REQUEST_ENTITY_TOO_LARGE: 413>: 'Request Entity Too Large', <HTTPStatus.REQUEST_URI_TOO_LONG: 414>: 'Request-URI Too Long', <HTTPStatus.UNSUPPORTED_MEDIA_TYPE: 415>: 'Unsupported Media Type', <HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: 416>: 'Requested Range Not Satisfiable', <HTTPStatus.EXPECTATION_FAILED: 417>: 'Expectation Failed', 418: "I'm a teapot", <HTTPStatus.MISDIRECTED_REQUEST: 421>: 'Misdirected Request', <HTTPStatus.UNPROCESSABLE_ENTITY: 422>: 'Unprocessable Entity', <HTTPStatus.LOCKED: 423>: 'Locked', <HTTPStatus.FAILED_DEPENDENCY: 424>: 'Failed Dependency', <HTTPStatus.UPGRADE_REQUIRED: 426>: 'Upgrade Required', <HTTPStatus.PRECONDITION_REQUIRED: 428>: 'Precondition Required', <HTTPStatus.TOO_MANY_REQUESTS: 429>: 'Too Many Requests', <HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE: 431>: 'Request Header Fields Too Large', <HTTPStatus.UNAVAILABLE_FOR_LEGAL_REASONS: 451>: 'Unavailable For Legal Reasons', <HTTPStatus.INTERNAL_SERVER_ERROR: 500>: 'Internal Server Error', <HTTPStatus.NOT_IMPLEMENTED: 501>: 'Not Implemented', <HTTPStatus.BAD_GATEWAY: 502>: 'Bad Gateway', <HTTPStatus.SERVICE_UNAVAILABLE: 503>: 'Service Unavailable', <HTTPStatus.GATEWAY_TIMEOUT: 504>: 'Gateway Timeout', <HTTPStatus.HTTP_VERSION_NOT_SUPPORTED: 505>: 'HTTP Version Not Supported', <HTTPStatus.VARIANT_ALSO_NEGOTIATES: 506>: 'Variant Also Negotiates', <HTTPStatus.INSUFFICIENT_STORAGE: 507>: 'Insufficient Storage', <HTTPStatus.LOOP_DETECTED: 508>: 'Loop Detected', <HTTPStatus.NOT_EXTENDED: 510>: 'Not Extended', <HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED: 511>: 'Network Authentication Required'}¶ A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)
-
app
()¶ -
default_app
()¶ Return the current Default Application. Actually, these are callable instances of
AppStack
and implement a stack-like API.
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', callback=None, **options)¶ -
get
(...)¶ -
post
(...)¶ -
put
(...)¶ -
delete
(...)¶ Decorator to install a route to the current default application. See
Bottle.route()
for details.
-
error
(...)¶ Decorator to install an error handler to the current default application. See
Bottle.error()
for details.
WSGI and HTTP Utilities¶
-
parse_auth
(header)[source]¶ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
Encode and sign a pickle-able object. Return a (byte) string
Verify and decode an encoded string. Return an object or None.
Return True if the argument looks like a encoded cookie.
-
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'
-
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
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.
-
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.
-
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.
-
-
class
HeaderDict
(*a, **ka)[source]¶ A case-insensitive version of
MultiDict
that defaults to replace the old value instead of appending it.-
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.
-
-
class
FormsDict
(*a, **k)[source]¶ This
MultiDict
subclass is used to store request form data. Additionally to the normal dict-like item access methods (which return unmodified data as native strings), this container also supports attribute-like access to its values. Attributes are automatically de- or recoded to matchinput_encoding
(default: ‘utf8’). Missing attributes default to an empty string.-
input_encoding
= 'utf8'¶ Encoding used for attribute values.
-
recode_unicode
= True¶ If true (default), unicode strings are first encoded with latin1 and then decoded to match
input_encoding
.
-
decode
(encoding=None)[source]¶ Returns a copy with all keys and values de- or recoded to match
input_encoding
. Some libraries (e.g. WTForms) want a unicode dictionary.
-
-
class
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.
-
-
class
AppStack
[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.
-
-
class
ResourceManager
(base='./', opener=<built-in function open>, cachemode='all')[source]¶ This class manages a list of search paths and helps to find and open application-bound resources (files).
Parameters: - base – default value for
add_path()
calls. - opener – callable used to open resources.
- cachemode – controls which lookups are cached. One of ‘all’, ‘found’ or ‘none’.
-
path
= None¶ A list of search paths. See
add_path()
for details.
-
cache
= None¶ A cache for resolved paths.
res.cache.clear()
clears the cache.
-
add_path
(path, base=None, index=None, create=False)[source]¶ Add a new path to the list of search paths. Return False if the path does not exist.
Parameters: - path – The new search path. Relative paths are turned into an absolute and normalized form. If the path looks like a file (not ending in /), the filename is stripped off.
- base – Path used to absolutize relative search paths.
Defaults to
base
which defaults toos.getcwd()
. - index – Position within the list of search paths. Defaults to last index (appends to the list).
The base parameter makes it easy to reference files installed along with a python module or package:
res.add_path('./resources/', __file__)
- base – default value for
The Bottle
Class¶
-
class
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. -
resources
= None¶ A
ResourceManager
for application files
-
config
= None¶ A
ConfigDict
for app specific configuration.
-
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.
-
merge
(routes)[source]¶ Merge the routes of another
Bottle
application or a list ofRoute
objects into this application. The routes keep their ‘owner’, meaning that theRoute.app
attribute is not changed.
-
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.
-
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 orTrue
to remove all plugins. Return the list of removed plugins.
-
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.
-
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. RaiseHTTPError
(404/405) on a non-match.
-
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. SeeRouter
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)
equalsroute(...)(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()
).
-
delete
(path=None, method='DELETE', **options)[source]¶ Equals
route()
with aDELETE
method parameter.
-
hook
(name)[source]¶ Return a decorator that attaches a callback to a hook. Three hooks are currently implemented:
- before_request: Executed once before each request
- after_request: Executed once after each request
- app_reset: Called whenever
reset()
is called.
-
handle
(path, method='GET')[source]¶ (deprecated) Execute the first matching route callback and return the result.
HTTPResponse
exceptions are caught and returned. IfBottle.catchall
is true, other exceptions are caught as well and returned asHTTPError
instances (500).
-
-
class
Route
(app, rule, method, callback, name=None, plugins=None, skiplist=None, **config)[source]¶ 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.
-
app
= None¶ The application this route is installed to.
-
rule
= None¶ The path-rule string (e.g.
/wiki/:page
).
-
method
= None¶ The HTTP method as a string (e.g.
GET
).
-
callback
= None¶ The original callback with no plugins applied. Useful for introspection.
-
name
= None¶ The name of the route (if specified) or
None
.
-
plugins
= None¶ A list of route-specific plugins (see
Bottle.route()
).
-
skiplist
= None¶ A list of plugins to not apply to this route (see
Bottle.route()
).
-
config
= None¶ Additional keyword arguments passed to the
Bottle.route()
decorator are stored in this dictionary. Used for route-specific plugin configuration and meta-data.
-
The Request
Object¶
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.
-
Request
¶ alias of
bottle.BaseRequest
-
class
BaseRequest
(environ=None)[source]¶ A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only.
Adding new attributes to a request actually adds them to the environ dictionary (as ‘bottle.request.ext.<name>’). This is the recommended way to store and access request-specific data.
-
MAX_PARAMS
= 100¶ Maximum number pr GET or POST parameters per request
-
environ
¶ The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.
-
path
¶ The value of
PATH_INFO
with exactly one prefixed slash (to fix broken clients and avoid the “empty path” edge case).
-
method
¶ The
REQUEST_METHOD
value as an uppercase string.
-
headers
[source]¶ A
WSGIHeaderDict
that provides case-insensitive access to HTTP request headers.
-
get_header
(name, default=None)[source]¶ Return the value of a request header, or a given default value.
Cookies parsed into a
FormsDict
. Signed cookies are NOT decoded. Useget_cookie()
if you expect signed cookies.
Return the content of a cookie. To read a Signed Cookie, the secret must match the one used to create the cookie (see
BaseResponse.set_cookie()
). If anything goes wrong (missing cookie or wrong signature), return a default value.
-
query
[source]¶ The
query_string
parsed into aFormsDict
. These values are sometimes called “URL arguments” or “GET parameters”, but not to be confused with “URL wildcards” as they are provided by theRouter
.
-
forms
[source]¶ Form values parsed from an url-encoded or multipart/form-data encoded POST or PUT request body. The result is retuned as a
FormsDict
. All keys and values are strings. File uploads are stored separately infiles
.
-
params
[source]¶ A
FormsDict
with the combined values ofquery
andforms
. File uploads are stored infiles
.
-
files
[source]¶ File uploads parsed from an url-encoded or multipart/form-data encoded POST or PUT request body. The values are instances of
cgi.FieldStorage
. The most important attributes are:- filename
- The filename, if specified; otherwise None; this is the client side filename, not the file name on which it is stored (that’s a temporary file you don’t deal with)
- file
- The file(-like) object from which you can read the data.
- value
- The value as a string; for file uploads, this transparently reads the file every time you request the value. Do not do this on big files.
-
json
[source]¶ If the
Content-Type
header isapplication/json
, this property holds the parsed content of the request body. Only requests smaller thanMEMFILE_MAX
are processed to avoid memory exhaustion.
-
body
¶ The HTTP request body as a seek-able file-like object. Depending on
MEMFILE_MAX
, this is either a temporary file or aio.BytesIO
instance. Accessing this property for the first time reads and replaces thewsgi.input
environ variable. Subsequent accesses just do a seek(0) on the file object.
-
POST
[source]¶ The values of
forms
andfiles
combined into a singleFormsDict
. Values are either strings (form values) or instances ofcgi.FieldStorage
(file uploads).
-
url
¶ The full request URI including hostname and scheme. If your app lives behind a reverse proxy or load balancer and you get confusing results, make sure that the
X-Forwarded-Host
header is set correctly.
-
urlparts
[source]¶ The
url
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 the server.
-
fullpath
¶ Request path including
script_name
(if present).
-
script_name
¶ The initial portion of the URL’s path that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes.
-
path_shift
(shift=1)[source]¶ - Shift path segments from
path
toscript_name
and - vice versa.
Parameters: shift – The number of path segments to shift. May be negative to change the shift direction. (default: 1) - Shift path segments from
-
content_length
¶ The request body length as an integer. The client is responsible to set this header. Otherwise, the real length of the body is unknown and -1 is returned. In this case,
body
will be empty.
-
content_type
¶ The Content-Type header as a lowercase-string (default: empty).
-
is_xhr
¶ True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the X-Requested-With header (most of the popular libraries do).
-
auth
¶ HTTP authentication data as a (user, password) tuple. This implementation currently supports basic (not digest) authentication only. If the authentication happened at a higher level (e.g. in the front web-server or a middleware), the password field is None, but the user field is looked up from the
REMOTE_USER
environ variable. On any errors, None is returned.
-
remote_route
¶ A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the
`X-Forwarded-For
header. Note that this information can be forged by malicious clients.
-
remote_addr
¶ The client IP as a string. Note that this information can be forged by malicious clients.
-
The module-level bottle.request
is a proxy object (implemented in LocalRequest
) and always refers to the current request, or in other words, the request that is currently processed by the request handler in the current thread. This thread locality ensures that you can safely use a global instance in a multi-threaded environment.
-
class
LocalRequest
(environ=None)[source]¶ A thread-local subclass of
BaseRequest
with a different set of attribues for each thread. There is usually only one global instance of this class (request
). If accessed during a request/response cycle, this instance always refers to the current request (even on a multithreaded server).-
bind
(environ=None)¶ Wrap a WSGI environ dictionary.
-
environ
¶ Thread-local property stored in
_lctx.request_environ
-
The Response
Object¶
The Response
class stores the HTTP status code as well as headers and cookies that are to be sent to the client. Similar to bottle.request
there is a thread-local bottle.response
instance that can be used to adjust the current response. Moreover, you can instantiate Response
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 of
bottle.BaseResponse
-
class
BaseResponse
(body='', status=None, **headers)[source]¶ Storage class for a response body as well as headers and cookies.
This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers.
-
status_line
¶ The HTTP status line as a string (e.g.
404 Not Found
).
-
status_code
¶ The HTTP status code as an integer (e.g. 404).
-
status
¶ A writeable property to change the HTTP response status. It accepts either a numeric code (100-999) or a string with a custom reason phrase (e.g. “404 Brain not found”). Both
status_line
andstatus_code
are updated accordingly. The return value is always a status string.
-
headers
¶ An instance of
HeaderDict
, a case-insensitive dict-like view on the response headers.
-
get_header
(name, default=None)[source]¶ Return the value of a previously defined header. If there is no header with that name, return a default value.
-
set_header
(name, value)[source]¶ Create a new response header, replacing any previously defined headers with the same name.
-
iter_headers
()[source]¶ Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.
-
headerlist
¶ 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.
-
charset
¶ Return the charset specified in the content-type header (default: utf8).
-
COOKIES
¶ A dict-like SimpleCookie instance. This should not be used directly. See
set_cookie()
.
Create a new cookie or replace an old one. If the secret parameter is set, create a Signed 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 are supported by
cookie.Morsel
, including:Parameters: - max_age – 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).
If neither expires nor max_age is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed).
Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side.
Delete a cookie. Be sure to use the same domain and path settings as used to create the cookie.
-
-
class
LocalResponse
(body='', status=None, **headers)[source]¶ A thread-local subclass of
BaseResponse
with a different set of attribues for each thread. There is usually only one global instance of this class (response
). Its attributes are used to build the HTTP response at the end of the request/response cycle.-
bind
(body='', status=None, **headers)¶ Initialize self. See help(type(self)) for accurate signature.
-
body
¶ Thread-local property stored in
_lctx.response_body
-
The following two classes can be raised as an exception. The most noticeable difference is that bottle invokes error handlers for HTTPError
, but not for HTTPResponse
or other response types.
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)[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
search
(name, lookup=[])[source]¶ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
-
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).
-
-
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.
-
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