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) 2012, Marcel Hellkamp. License: MIT (see LICENSE for details)
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Adapter for Google App Engine.
Bases: list
A stack-like list. Calling it returns the head of the stack.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested.
Bases: object
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.
Maximum number pr GET or POST parameters per request
The values of forms and files combined into a single FormsDict. Values are either strings (form values) or instances of cgi.FieldStorage (file uploads).
Bottle application handling this request.
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.
The HTTP request body as a seek-able file-like object. Depending on MEMFILE_MAX, this is either a temporary file or a io.BytesIO instance. Accessing this property for the first time reads and replaces the wsgi.input environ variable. Subsequent accesses just do a seek(0) on the file object.
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.
The Content-Type header as a lowercase-string (default: empty).
Cookies parsed into a FormsDict. Signed cookies are NOT decoded. Use get_cookie() if you expect signed cookies.
The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.
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:
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 in files.
Request path including script_name (if present).
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.
Return the value of a request header, or a given default value.
A WSGIHeaderDict that provides case-insensitive access to HTTP request headers.
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).
If the Content-Type header is application/json, this property holds the parsed content of the request body. Only requests smaller than MEMFILE_MAX are processed to avoid memory exhaustion.
The REQUEST_METHOD value as an uppercase string.
The value of PATH_INFO with exactly one prefixed slash (to fix broken clients and avoid the “empty path” edge case).
Parameters: | shift – The number of path segments to shift. May be negative to change the shift direction. (default: 1) |
---|
The query_string parsed into a FormsDict. These values are sometimes called “URL arguments” or “GET parameters”, but not to be confused with “URL wildcards” as they are provided by the Router.
The client IP as a string. Note that this information can be forged by malicious clients.
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.
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.
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.
The url string as an urlparse.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.
Bases: object
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.
A dict-like SimpleCookie instance. This should not be used directly. See set_cookie().
Add an additional response header, not removing duplicates.
Return the charset specified in the content-type header (default: utf8).
Current value of the ‘Content-Length’ header.
Current value of the ‘Content-Type’ header.
Returns a copy of self.
Delete a cookie. Be sure to use the same domain and path settings as used to create the cookie.
Return the value of a previously defined header. If there is no header with that name, return a default value.
WSGI conform list of (header, value) tuples.
An instance of HeaderDict, a case-insensitive dict-like view on the response headers.
Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.
Create a new cookie or replace an old one. If the secret parameter is set, create a Signed Cookie (described below).
Parameters: |
|
---|
Additionally, this method accepts all RFC 2109 attributes that are supported by cookie.Morsel, including:
Parameters: |
|
---|
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.
Create a new response header, replacing any previously defined headers with the same name.
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 and status_code are updated accordingly. The return value is always a status string.
The HTTP status code as an integer (e.g. 404).
The HTTP status line as a string (e.g. 404 Not Found).
Bases: object
Base class and minimal API for template adapters
This reads or sets the global settings stored in class.settings.
Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.
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).
Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Fast server written in C: https://github.com/jonashaag/bjoern
Bases: object
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. |
---|
If true, most exceptions are caught and returned as HTTPError
Close the application and all installed plugins.
A ConfigDict for app specific configuration.
Decorator: Register an output handler for a HTTP error code
Return a string that matches a named route
(deprecated) Execute the first matching route callback and return the result. HTTPResponse exceptions are caught and returned. If Bottle.catchall is true, other exceptions are caught as well and returned as HTTPError instances (500).
Return a decorator that attaches a callback to a hook. Three hooks are currently implemented:
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.
Search for a matching route and return a (Route , urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise HTTPError (404/405) on a non-match.
Merge the routes of another Bottle application or a list of Route objects into this application. The routes keep their ‘owner’, meaning that the Route.app attribute is not changed.
Mount an application (Bottle or plain WSGI) to a specific URL prefix. Example:
root_app.mount('/admin/', admin_app)
Parameters: |
|
---|
All other parameters are passed to the underlying route() call.
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.
A ResourceManager for application files
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. See Router for syntax details.
Parameters: |
|
---|
Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see Plugin.apply()).
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 or True to remove all plugins. Return the list of removed plugins.
The bottle WSGI-interface.
Bases: exceptions.Exception
A base class for exceptions used by bottle.
Bases: dict
A dict-subclass with some extras: You can access keys like attributes. Uppercase attributes create new ConfigDicts and act as name-spaces. Other missing attributes return None. Calling a ConfigDict updates its values and returns itself.
>>> cfg = ConfigDict()
>>> cfg.Namespace.value = 5
>>> cfg.OtherNamespace(a=1, b=2)
>>> cfg
{'Namespace': {'value': 5}, 'OtherNamespace': {'a': 1, 'b': 2}}
Bases: object
Property that maps to a key in a local dict-like attribute.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested.
The default template used for error pages. Override with @error()
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Extremely fast webserver using libev. See http://www.fapws.org/
Bases: threading.Thread
Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old.
Is one of ‘reload’, ‘error’ or ‘exit’
Bases: vnc_cfg_api_server.bottle.MultiDict
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 match input_encoding (default: ‘utf8’). Missing attributes default to an empty string.
Returns a copy with all keys and values de- or recoded to match input_encoding. Some libraries (e.g. WTForms) want a unicode dictionary.
Encoding used for attribute values.
If true (default), unicode strings are first encoded with latin1 and then decoded to match input_encoding.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested. Options:
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested. See http://gunicorn.org/configure.html for options.
A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)
Bases: vnc_cfg_api_server.bottle.MultiDict
A case-insensitive version of MultiDict that defaults to replace the old value instead of appending it.
Bases: vnc_cfg_api_server.bottle.BaseRequest
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).
Wrap a WSGI environ dictionary.
Thread-local property stored in _lctx.request_environ
Bases: vnc_cfg_api_server.bottle.BaseResponse
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.
Thread-local property stored in _lctx.response_body
Bases: _abcoll.MutableMapping
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.
Add a new value to the list of values for this key.
Return the most recent value for a key.
Parameters: |
|
---|
Return a (possibly empty) list of values for a key.
Return a (possibly empty) list of values for a key.
Aliases for WTForms to mimic other multi-dict APIs (Django)
Replace the list of values with a single value.
alias of BaseRequest
Bases: object
This class manages a list of search paths and helps to find and open application-bound resources (files).
Parameters: |
|
---|
Add a new path to the list of search paths. Return False if the path does not exist.
Parameters: |
|
---|
The base parameter makes it easy to reference files installed along with a python module or package:
res.add_path('./resources/', __file__)
A cache for resolved paths. res.cache.clear() clears the cache.
Search for a resource and return an absolute file path, or None.
The path list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups.
Find a resource and return a file object, or raise IOError.
A list of search paths. See add_path() for details.
alias of BaseResponse
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested.
Bases: object
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.
Yield all Plugins affecting this route.
The application this route is installed to.
The original callback with no plugins applied. Useful for introspection.
Additional keyword arguments passed to the Bottle.route() decorator are stored in this dictionary. Used for route-specific plugin configuration and meta-data.
The HTTP method as a string (e.g. GET).
The name of the route (if specified) or None.
A list of route-specific plugins (see Bottle.route()).
Do all on-demand work immediately (useful for debugging).
Forget any cached values. The next time call is accessed, all plugins are re-applied.
The path-rule string (e.g. /wiki/:page).
A list of plugins to not apply to this route (see Bottle.route()).
Bases: vnc_cfg_api_server.bottle.RouteError
The route could not been built
Bases: vnc_cfg_api_server.bottle.BottleException
This is a base class for all routing related exceptions
Bases: vnc_cfg_api_server.bottle.BottleException
If raised by a plugin or request handler, the route is reset and all plugins are re-applied.
Bases: vnc_cfg_api_server.bottle.RouteError
The route parser found something not supported by this router
Bases: object
A Router is an ordered collection of route->target pairs. It is used to efficiently match WSGI requests against a number of routes and return the first target that satisfies the request. The target may be anything, usually a string, ID or callable object. A route consists of a path-rule and a HTTP method.
The path-rule is either a static path (e.g. /contact) or a dynamic path that contains wildcards (e.g. /wiki/<page>). The wildcard syntax and details on the matching order are described in docs:routing.
Add a new route or replace the target for an existing route.
Add a filter. The provided function is called with the configuration string 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.
Build an URL by filling the wildcards in a rule.
Return a (target, url_agrs) tuple or raise HTTPError(400/404/405).
Parses a rule into a (name, filter, conf) token stream. If mode is None, name contains a static rule part.
Sorry for the mess. It works. Trust me.
If true, static routes are no longer checked first.
Bases: vnc_cfg_api_server.bottle.BaseTemplate
Deprecated, do not use.
Bases: object
This plugin applies the view() decorator to all routes with a template config parameter. If the parameter is a tuple, the second element must be a dict with additional options (e.g. template_engine) or default variables for the template.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
The super hyped asynchronous server by facebook. Untested.
Bases: vnc_cfg_api_server.bottle.ServerAdapter
Untested.
Bases: _abcoll.MutableMapping
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.)
List of keys that do not have a HTTP_ prefix.
Return the header value as is (may be bytes or unicode).
Aborts execution and causes a HTTP error.
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
Bases: object
A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property.
Verify and decode an encoded string. Return an object or None.
Encode and sign a pickle-able object. Return a (byte) string
Return True if the argument looks like a encoded cookie.
Change the debug level. There is only one debug level supported at the moment.
Decorator: Register an output handler for a HTTP error code
A virtual package that redirects import statements. Example: import bottle.ext.sqlite actually imports bottle_sqlite.
Return a decorator that attaches a callback to a hook. Three hooks are currently implemented:
Escape HTML special characters &<> and quotes '".
Escape and quote a string to be used as an HTTP attribute.
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.
Bases: object
A property that caches itself to the class object.
Import a module or fetch an object from a module.
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 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.
A thread-safe namespace. Not used by Bottle.
Return a callable that relays calls to the current default app.
Mount an application (Bottle or plain WSGI) to a specific URL prefix. Example:
root_app.mount('/admin/', admin_app)
Parameters: |
|
---|
All other parameters are passed to the underlying route() call.
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
Returns: | The modified paths. |
---|---|
Parameters: |
|
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
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).
A thread-safe instance of LocalResponse. It is used to change the HTTP response for the current request.
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. See Router for syntax details.
Parameters: |
|
---|
Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see Plugin.apply()).
Start a server instance. This method blocks until the server terminates.
Parameters: |
|
---|
Open a file in a safe way and return HTTPResponse with status code 200, 305, 401 or 404. Set Content-Type, Content-Encoding, Content-Length and Last-Modified header. Obey If-Modified-Since header and HEAD requests.
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).
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 or True to remove all plugins. Return the list of removed plugins.
Return a string that matches a named route
Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403).
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.
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'