Simple ServerAdapter class diagram
Simple DictProperty class diagram :
Simple HooksPlugin class diagram :
Simple JSONPlugin class diagram :
Simple HeaderProperty class diagram :
Simple BaseResponse class diagram :
Simple TemplatePlugin class diagram :
Simple BaseTemplate class diagram :
Simple DictMixin class diagram :
Simple Router class diagram :
Simple WSGIFileWrapper class diagram :
Simple Bottle class diagram :
Simple TypeFilterPlugin class diagram :
Simple list class diagram :
webui
Package¶bottlecore
Module¶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) 2011, Marcel Hellkamp. License: MIT (see LICENSE.txt for details)
shinken.webui.bottlecore.
AppEngineServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Adapter for Google App Engine.
quiet
= True¶shinken.webui.bottlecore.
AppStack
[source]¶Bases: list
A stack-like list. Calling it returns the head of the stack.
shinken.webui.bottlecore.
AutoServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested.
adapters
= [<class 'shinken.webui.bottlecore.PasteServer'>, <class 'shinken.webui.bottlecore.CherryPyServer'>, <class 'shinken.webui.bottlecore.TwistedServer'>, <class 'shinken.webui.bottlecore.WSGIRefServer'>]¶shinken.webui.bottlecore.
BaseRequest
(environ)[source]¶Bases: _abcoll.MutableMapping
A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only.
POST
[source]¶The values of forms
and files
combined into a single
MultiDict
. Values are either strings (form values) or
instances of cgi.FieldStorage
(file uploads).
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.
body
¶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.
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.
Cookies parsed into a dictionary. Signed cookies are NOT decoded.
Use get_cookie()
if you expect signed cookies.
environ
= None¶The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.
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:
forms
[source]¶Form values parsed from an url-encoded or multipart/form-data
encoded POST or PUT request body. The result is returned as a
MultiDict
. All keys and values are strings. File uploads
are stored separately in files
.
fullpath
¶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.
headers
[source]¶A WSGIHeaderDict
that provides case-insensitive access to
HTTP request headers.
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).
json
[source]¶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.
method
¶The REQUEST_METHOD
value as an uppercase string.
params
[source]¶A MultiDict
with the combined values of query
and
forms
. File uploads are stored in files
.
path
¶The value of PATH_INFO
with exactly one prefixed slash (to fix
broken clients and avoid the “empty path” edge case).
path_shift
(shift=1)[source]¶Shift path segments from path
to script_name
and
vice versa.:param shift: The number of path segments to shift. May be negative
to change the shift direction. (default: 1)
query
[source]¶The query_string
parsed into a MultiDict
. 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
.
remote_addr
¶The client IP as a string. Note that this information can be forged by malicious clients.
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.
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 property returns an empty string, or a path with leading and tailing slashes.
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 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.
shinken.webui.bottlecore.
BaseResponse
(body='', status=None, **headers)[source]¶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.
COOKIES
¶A dict-like SimpleCookie instance. This should not be used directly.
See set_cookie()
.
bad_headers
= {304: set(['Content-Length', 'Content-Language', 'Content-Encoding', 'Content-Md5', 'Last-Modified', 'Content-Range', 'Allow', 'Content-Type']), 204: set(['Content-Type'])}¶Header blacklist for specific response codes (rfc2616 section 10.2.3 and 10.3.5)
body
= None¶The response body as one of the supported data types.
charset
¶Return the charset specified in the content-type header (default: utf8).
content_length
¶Current value of the ‘Content-Length’ header.
content_type
¶Current value of the ‘Content-Type’ header.
default_content_type
= 'text/html; charset=UTF-8'¶default_status
= 200¶Delete a cookie. Be sure to use the same domain and path settings as used to create the cookie.
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.
headerlist
¶WSGI conform list of (header, value) tuples.
headers
¶An instance of HeaderDict
, a case-insensitive dict-like
view on the response headers.
iter_headers
()[source]¶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).:param key: the name of the cookie. :param value: the value of the cookie.:param secret: a signature key required for signed cookies.
Additionally, this method accepts all RFC 2109 attributes that are
supported by cookie.Morsel
, including::param max_age: maximum
age in seconds.
(default: None):param expires: a datetime object or UNIX timestamp.
(default: None):param domain:
the domain that is allowed to read the cookie.
(default: current domain):param path: limits the cookie to a given
path (default: /
):param secure: limit the cookie to HTTPS connections
(default: off).
:param 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.
set_header
(name, value, append=False)[source]¶Create a new response header, replacing any previously defined
headers with the same name. This equals response[name] = value
.:param append:
Do not delete previously defined headers. This can
result in two (or more) headers having the same name.
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
and
status_line
are updates accordingly. The return value is
always a numeric code.
status_code
= None¶The HTTP status code as an integer (e.g. 404).
Do not change it directly, see status
.
shinken.webui.bottlecore.
BaseTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: object
Base class and minimal API for template adapters
defaults
= {}¶extentions
= ['tpl', 'html', 'thtml', 'stpl']¶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).
search
(name, lookup=[])[source]¶Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
settings
= {}¶shinken.webui.bottlecore.
BjoernServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Screamingly fast server written in C: https://github.com/jonashaag/bjoern
shinken.webui.bottlecore.
Bottle
(catchall=True, autojson=True, config=None)[source]¶Bases: object
WSGI application
delete
(path=None, method='DELETE', **options)[source]¶Equals route()
with a DELETE
method parameter.
handle
(path, method='GET')[source]¶(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).
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.
match
(environ)[source]¶(deprecated) Search for a matching route and return a
(callback, urlargs) tuple.
The first element is the associated route callback with plugins
applied. The second value is a dictionary with parameters extracted
from the URL. The Router
raises HTTPError
(404/405)
on a non-match.
mount
(app, prefix, **options)[source]¶Mount an application to a specific URL prefix. The prefix is added
to SCIPT_PATH and removed from PATH_INFO before the sub-application
is called.:param app: an instance of Bottle
.:param prefix:
path prefix used as a mount-point.
All other parameters are passed to the underlying route()
call.
reset
(id=None)[source]¶Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.
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. See Router
for syntax
details.:param 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.:param method: HTTP method (GET, POST, PUT, ...) or a list of methods to listen to. (default: GET):param callback: An optional shortcut to avoid the decorator syntax.route(..., callback=func)
equalsroute(...)(func)
:param name: The name for this route. (default: None):param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins.:param 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()
).
uninstall
(plugin)[source]¶Uninstall plugins. Pass an instance to remove a specific plugin.
Pass a type object to remove all plugins that match that type.
Subclasses are not removed. Pass a string to remove all plugins with
a matching name
attribute. Pass True
to remove all plugins.
The list of affected plugins is returned.
shinken.webui.bottlecore.
BottleException
[source]¶Bases: exceptions.Exception
A base class for exceptions used by bottle.
shinken.webui.bottlecore.
CGIServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
quiet
= True¶shinken.webui.bottlecore.
CheetahTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlecore.
DictProperty
(attr, key=None, read_only=False)[source]¶Bases: object
Property that maps to a key in a local dict-like attribute.
shinken.webui.bottlecore.
DieselServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested.
shinken.webui.bottlecore.
ERROR_PAGE_TEMPLATE
= '\n%try:\n %from shinken.webui.bottlecore import DEBUG, HTTP_CODES, request, touni\n %status_name = HTTP_CODES.get(e.status, \'Unknown\').title()\n <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n <html>\n <head>\n <title>Error {{e.status}}: {{status_name}}</title>\n <style type="text/css">\n html {background-color: #eee; font-family: sans;}\n body {background-color: #fff; border: 1px solid #ddd;\n padding: 15px; margin: 15px;}\n pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}\n </style>\n </head>\n <body>\n <h1>Error {{e.status}}: {{status_name}}</h1>\n <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>\n caused an error:</p>\n <pre>{{e.output}}</pre>\n %if DEBUG and e.exception:\n <h2>Exception:</h2>\n <pre>{{repr(e.exception)}}</pre>\n %end\n %if DEBUG and e.traceback:\n <h2>Traceback:</h2>\n <pre>{{e.traceback}}</pre>\n %end\n </body>\n </html>\n%except ImportError:\n <b>ImportError:</b> Could not generate the error page. Please add bottle to\n the import path.\n%end\n'¶The default template used for error pages. Override with @error()
shinken.webui.bottlecore.
EventletServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested
shinken.webui.bottlecore.
FapwsServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Extremely fast webserver using libev. See http://www.fapws.org/
shinken.webui.bottlecore.
FileCheckerThread
(lockfile, interval)[source]¶Bases: threading.Thread
Thread that periodically checks for changed module files.
shinken.webui.bottlecore.
GeventServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested. Options:
shinken.webui.bottlecore.
GunicornServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested.
shinken.webui.bottlecore.
HTTPError
(code=500, output='Unknown Error', exception=None, traceback=None, header=None)[source]¶Bases: shinken.webui.bottlecore.HTTPResponse
Used to generate an error page
shinken.webui.bottlecore.
HTTPResponse
(output='', status=200, header=None)[source]¶Bases: shinken.webui.bottlecore.BottleException
Used to break execution and immediately finish the response
shinken.webui.bottlecore.
HTTP_CODES
= {200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 418: "I'm a teapot", 100: 'Continue', 101: 'Switching Protocols', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: '(Unused)', 307: 'Temporary Redirect', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported'}¶A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)
shinken.webui.bottlecore.
HeaderDict
(*a, **ka)[source]¶Bases: shinken.webui.bottlecore.MultiDict
A case-insensitive version of MultiDict
that defaults to
replace the old value instead of appending it.
shinken.webui.bottlecore.
HeaderProperty
(name, reader=None, writer=<type 'str'>, default='')[source]¶Bases: object
shinken.webui.bottlecore.
JSONPlugin
(json_dumps=<function dumps>)[source]¶Bases: object
name
= 'json'¶shinken.webui.bottlecore.
Jinja2Template
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlecore.
LocalRequest
[source]¶Bases: shinken.webui.bottlecore.BaseRequest
, thread._local
A thread-local subclass of BaseRequest
.
bind
(environ)¶Wrap a WSGI environ dictionary.
shinken.webui.bottlecore.
LocalResponse
(body='', status=None, **headers)[source]¶Bases: shinken.webui.bottlecore.BaseResponse
, thread._local
A thread-local subclass of BaseResponse
.
bind
(body='', status=None, **headers)¶shinken.webui.bottlecore.
MakoTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlecore.
MultiDict
(*a, **k)[source]¶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.
allitems
()¶get
(key, default=None, index=-1)[source]¶Return the current value for a key. The third index parameter defaults to -1 (last value).
items
()¶keys
()¶values
()¶shinken.webui.bottlecore.
Request
¶alias of LocalRequest
shinken.webui.bottlecore.
Response
¶alias of LocalResponse
shinken.webui.bottlecore.
RocketServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested. As requested in issue 63 https://github.com/defnull/bottle/issues/#issue/63
shinken.webui.bottlecore.
RouteBuildError
[source]¶Bases: shinken.webui.bottlecore.RouteError
The route could not been built
shinken.webui.bottlecore.
RouteError
[source]¶Bases: shinken.webui.bottlecore.BottleException
This is a base class for all routing related exceptions
shinken.webui.bottlecore.
RouteReset
[source]¶Bases: shinken.webui.bottlecore.BottleException
If raised by a plugin or request handler, the route is reset and all plugins are re-applied.
shinken.webui.bottlecore.
RouteSyntaxError
[source]¶Bases: shinken.webui.bottlecore.RouteError
The route parser found something not supported by this router
shinken.webui.bottlecore.
Router
[source]¶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). By default, wildcards consume characters up to the next slash (/). To change that, you may add a regular expression pattern (e.g. /wiki/:page#[a-z]+#).
For performance reasons, static routes (rules without wildcards) are checked first. Dynamic routes are searched in order. Try to avoid ambiguous or overlapping rules.
An optional name
parameter is used by build()
to identify
routes.
add
(rule, method, target, name=None)[source]¶Add a new route or replace the target for an existing route.
build
(_name, *anon, **args)[source]¶Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.
default
= '[^/]+'¶syntax
= <_sre.SRE_Pattern object>¶shinken.webui.bottlecore.
ServerAdapter
(host='127.0.0.1', port=8080, **config)[source]¶Bases: object
quiet
= False¶shinken.webui.bottlecore.
SimpleTALTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: shinken.webui.bottlecore.BaseTemplate
Untested!
shinken.webui.bottlecore.
SimpleTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: shinken.webui.bottlecore.BaseTemplate
blocks
= ('if', 'elif', 'else', 'try', 'except', 'finally', 'for', 'while', 'with', 'def', 'class')¶dedent_blocks
= ('elif', 'else', 'except', 'finally')¶re_pytokens
= <_sre.SRE_Pattern object at 0x4d0db10>¶shinken.webui.bottlecore.
TemplatePlugin
[source]¶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.
name
= 'template'¶shinken.webui.bottlecore.
TornadoServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
The super hyped asynchronous server by facebook. Untested.
shinken.webui.bottlecore.
TwistedServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlecore.ServerAdapter
Untested.
shinken.webui.bottlecore.
WSGIHeaderDict
(environ)[source]¶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.)
shinken.webui.bottlecore.
abort
(code=500, text='Unknown Error: Application stopped.')[source]¶Aborts execution and causes a HTTP error.
shinken.webui.bottlecore.
auth_basic
(check, realm='private', text='Access denied')[source]¶Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
shinken.webui.bottlecore.
cached_property
(func)[source]¶A property that, if accessed, replaces itself with the computed value. Subsequent accesses won’t call the getter again.
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.
shinken.webui.bottlecore.
debug
(mode=True)[source]¶Change the debug level. There is only one debug level supported at the moment.
shinken.webui.bottlecore.
error
(*a, **ka)¶Decorator: Register an output handler for a HTTP error code
shinken.webui.bottlecore.
ext
= <module 'shinken.webui.bottlecore.ext' from '<virtual>'>¶A virtual package that redirects import statements.
Example: import bottle.ext.sqlite
actually imports bottle_sqlite.
shinken.webui.bottlecore.
hook
(*a, **ka)¶Return a decorator that attaches a callback to a hook.
shinken.webui.bottlecore.
install
(*a, **ka)¶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.
shinken.webui.bottlecore.
lazy_attribute
(func)[source]¶Bases: object
A property that caches itself to the class object.
shinken.webui.bottlecore.
load_app
(target)[source]¶Load a bottle application based on a target string and return the application object.
If the target is an import path (e.g. package.module), the application stack is used to isolate the routes defined in that module. If the target contains a colon (e.g. package.module:myapp) the module variable specified after the colon is returned instead.
shinken.webui.bottlecore.
local
= <thread._local object>¶A thread-save namespace. Not used by Bottle.
shinken.webui.bottlecore.
make_default_app_wrapper
(name)[source]¶Return a callable that relays calls to the current default app.
shinken.webui.bottlecore.
mount
(*a, **ka)¶Mount an application to a specific URL prefix. The prefix is added
to SCIPT_PATH and removed from PATH_INFO before the sub-application
is called.:param app: an instance of Bottle
.:param prefix:
path prefix used as a mount-point.
All other parameters are passed to the underlying route()
call.
shinken.webui.bottlecore.
parse_auth
(header)[source]¶Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
shinken.webui.bottlecore.
parse_date
(ims)[source]¶Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
shinken.webui.bottlecore.
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.:param script_name: The SCRIPT_NAME path.:param script_name: |
---|
shinken.webui.bottlecore.
redirect
(url, code=303)[source]¶Aborts execution and causes a 303 redirect.
shinken.webui.bottlecore.
request
= <shinken.webui.bottlecore.LocalRequest object>¶A thread-save instance of Request
representing the current request.
shinken.webui.bottlecore.
response
= <shinken.webui.bottlecore.LocalResponse object>¶A thread-save instance of Response
used to build the HTTP response.
shinken.webui.bottlecore.
route
(*a, **ka)¶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.:param 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.:param method: HTTP method (GET, POST, PUT, ...) or a list of methods to listen to. (default: GET):param callback: An optional shortcut to avoid the decorator syntax.route(..., callback=func)
equalsroute(...)(func)
:param name: The name for this route. (default: None):param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins.:param 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()
).
shinken.webui.bottlecore.
run
(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs)[source]¶Start a server instance. This method blocks until the server terminates.:param app:
WSGI application or target string supported by
load_app()
. (default: default_app()
):param server: Server adapter to use.
See server_names
keys for valid names or pass a ServerAdapter
subclass.
(default: wsgiref):param 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):param port: Server port
to bind to. Values below 1024 require root privileges.
(default: 8080):param reloader: Start auto-reloading server?
(default: False):param interval: Auto-reloader interval in seconds (default:
1):param quiet: Suppress output to stdout and stderr? (default: False):param options:
Options passed to the server adapter.
shinken.webui.bottlecore.
static_file
(filename, root, mimetype='auto', download=False)[source]¶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.
shinken.webui.bottlecore.
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).
shinken.webui.bottlecore.
tonat
(data, enc='utf8')¶Convert anything to native strings
shinken.webui.bottlecore.
uninstall
(*a, **ka)¶Uninstall plugins. Pass an instance to remove a specific plugin.
Pass a type object to remove all plugins that match that type.
Subclasses are not removed. Pass a string to remove all plugins with
a matching name
attribute. Pass True
to remove all plugins.
The list of affected plugins is returned.
shinken.webui.bottlecore.
url
(*a, **ka)¶Return a string that matches a named route
shinken.webui.bottlecore.
validate
(**vkargs)[source]¶Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403).
shinken.webui.bottlecore.
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.
shinken.webui.bottlecore.
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'
bottlewebui
Module¶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) 2011, Marcel Hellkamp. License: MIT (see LICENSE.txt for details)
shinken.webui.bottlewebui.
AppEngineServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Adapter for Google App Engine.
quiet
= True¶shinken.webui.bottlewebui.
AppStack
[source]¶Bases: list
A stack-like list. Calling it returns the head of the stack.
shinken.webui.bottlewebui.
AutoServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested.
adapters
= [<class 'shinken.webui.bottlewebui.PasteServer'>, <class 'shinken.webui.bottlewebui.CherryPyServer'>, <class 'shinken.webui.bottlewebui.TwistedServer'>, <class 'shinken.webui.bottlewebui.WSGIRefServer'>]¶shinken.webui.bottlewebui.
BaseRequest
(environ)[source]¶Bases: _abcoll.MutableMapping
A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only.
POST
[source]¶The values of forms
and files
combined into a single
MultiDict
. Values are either strings (form values) or
instances of cgi.FieldStorage
(file uploads).
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.
body
¶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.
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.
Cookies parsed into a dictionary. Signed cookies are NOT decoded.
Use get_cookie()
if you expect signed cookies.
environ
= None¶The wrapped WSGI environ dictionary. This is the only real attribute. All other attributes actually are read-only properties.
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:
forms
[source]¶Form values parsed from an url-encoded or multipart/form-data
encoded POST or PUT request body. The result is returned as a
MultiDict
. All keys and values are strings. File uploads
are stored separately in files
.
fullpath
¶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.
headers
[source]¶A WSGIHeaderDict
that provides case-insensitive access to
HTTP request headers.
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).
json
[source]¶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.
method
¶The REQUEST_METHOD
value as an uppercase string.
params
[source]¶A MultiDict
with the combined values of query
and
forms
. File uploads are stored in files
.
path
¶The value of PATH_INFO
with exactly one prefixed slash (to fix
broken clients and avoid the “empty path” edge case).
path_shift
(shift=1)[source]¶Shift path segments from path
to script_name
and
vice versa.:param shift: The number of path segments to shift. May be negative
to change the shift direction. (default: 1)
query
[source]¶The query_string
parsed into a MultiDict
. 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
.
remote_addr
¶The client IP as a string. Note that this information can be forged by malicious clients.
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.
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 property returns an empty string, or a path with leading and tailing slashes.
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 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.
shinken.webui.bottlewebui.
BaseResponse
(body='', status=None, **headers)[source]¶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.
COOKIES
¶A dict-like SimpleCookie instance. This should not be used directly.
See set_cookie()
.
bad_headers
= {304: set(['Content-Length', 'Content-Language', 'Content-Encoding', 'Content-Md5', 'Last-Modified', 'Content-Range', 'Allow', 'Content-Type']), 204: set(['Content-Type'])}¶Header blacklist for specific response codes (rfc2616 section 10.2.3 and 10.3.5)
body
= None¶The response body as one of the supported data types.
charset
¶Return the charset specified in the content-type header (default: utf8).
content_length
¶Current value of the ‘Content-Length’ header.
content_type
¶Current value of the ‘Content-Type’ header.
default_content_type
= 'text/html; charset=UTF-8'¶default_status
= 200¶Delete a cookie. Be sure to use the same domain and path settings as used to create the cookie.
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.
headerlist
¶WSGI conform list of (header, value) tuples.
headers
¶An instance of HeaderDict
, a case-insensitive dict-like
view on the response headers.
iter_headers
()[source]¶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).:param key: the name of the cookie. :param value: the value of the cookie.:param secret: a signature key required for signed cookies.
Additionally, this method accepts all RFC 2109 attributes that are
supported by cookie.Morsel
, including::param max_age: maximum age in seconds.
(default: None):param expires: a datetime object or UNIX timestamp.
(default: None):param domain:
the domain that is allowed to read the cookie.
(default: current domain):param path: limits the cookie to a given path
(default: /
):param secure: limit the cookie to HTTPS connections (default: off).
:param 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.
set_header
(name, value, append=False)[source]¶Create a new response header, replacing any previously defined
headers with the same name. This equals response[name] = value
.:param append:
Do not delete previously defined headers. This can
result in two (or more) headers having the same name.
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
and
status_line
are updates accordingly. The return value is
always a numeric code.
status_code
= None¶The HTTP status code as an integer (e.g. 404).
Do not change it directly, see status
.
shinken.webui.bottlewebui.
BaseTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: object
Base class and minimal API for template adapters
defaults
= {}¶extentions
= ['tpl', 'html', 'thtml', 'stpl']¶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).
search
(name, lookup=[])[source]¶Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
settings
= {}¶shinken.webui.bottlewebui.
BjoernServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Screamingly fast server written in C: https://github.com/jonashaag/bjoern
shinken.webui.bottlewebui.
Bottle
(catchall=True, autojson=True, config=None)[source]¶Bases: object
WSGI application
delete
(path=None, method='DELETE', **options)[source]¶Equals route()
with a DELETE
method parameter.
handle
(path, method='GET')[source]¶(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).
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.
match
(environ)[source]¶(deprecated) Search for a matching route and return a
(callback, urlargs) tuple.
The first element is the associated route callback with plugins
applied. The second value is a dictionary with parameters extracted
from the URL. The Router
raises HTTPError
(404/405)
on a non-match.
mount
(app, prefix, **options)[source]¶Mount an application to a specific URL prefix. The prefix is added
to SCIPT_PATH and removed from PATH_INFO before the sub-application
is called.:param app: an instance of Bottle
.:param prefix:
path prefix used as a mount-point.
All other parameters are passed to the underlying route()
call.
reset
(id=None)[source]¶Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.
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. See Router
for syntax
details.:param 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.:param method: HTTP method (GET, POST, PUT, ...)
or a list of methods to listen to. (default: GET):param callback: An optional
shortcut to avoid the decorator syntax. route(..., callback=func)
equals
route(...)(func)
:param name: The name for this route. (default: None):param apply:
A decorator or plugin or a list of plugins. These are applied to the route callback in
addition to installed plugins.:param 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()
).
uninstall
(plugin)[source]¶Uninstall plugins. Pass an instance to remove a specific plugin.
Pass a type object to remove all plugins that match that type.
Subclasses are not removed. Pass a string to remove all plugins with
a matching name
attribute. Pass True
to remove all plugins.
The list of affected plugins is returned.
shinken.webui.bottlewebui.
BottleException
[source]¶Bases: exceptions.Exception
A base class for exceptions used by bottle.
shinken.webui.bottlewebui.
CGIServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
quiet
= True¶shinken.webui.bottlewebui.
CheetahTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlewebui.
DictProperty
(attr, key=None, read_only=False)[source]¶Bases: object
Property that maps to a key in a local dict-like attribute.
shinken.webui.bottlewebui.
DieselServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested.
shinken.webui.bottlewebui.
ERROR_PAGE_TEMPLATE
= '\n%try:\n %from shinken.webui.bottlewebui import DEBUG, HTTP_CODES, request, touni\n %status_name = HTTP_CODES.get(e.status, \'Unknown\').title()\n <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n <html>\n <head>\n <title>Error {{e.status}}: {{status_name}}</title>\n <style type="text/css">\n html {background-color: #eee; font-family: sans;}\n body {background-color: #fff; border: 1px solid #ddd;\n padding: 15px; margin: 15px;}\n pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}\n </style>\n </head>\n <body>\n <h1>Error {{e.status}}: {{status_name}}</h1>\n <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>\n caused an error:</p>\n <pre>{{e.output}}</pre>\n %if DEBUG and e.exception:\n <h2>Exception:</h2>\n <pre>{{repr(e.exception)}}</pre>\n %end\n %if DEBUG and e.traceback:\n <h2>Traceback:</h2>\n <pre>{{e.traceback}}</pre>\n %end\n </body>\n </html>\n%except ImportError:\n <b>ImportError:</b> Could not generate the error page. Please add bottle to\n the import path.\n%end\n'¶The default template used for error pages. Override with @error()
shinken.webui.bottlewebui.
EventletServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested
shinken.webui.bottlewebui.
FapwsServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Extremely fast webserver using libev. See http://www.fapws.org/
shinken.webui.bottlewebui.
FileCheckerThread
(lockfile, interval)[source]¶Bases: threading.Thread
Thread that periodically checks for changed module files.
shinken.webui.bottlewebui.
GeventServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested. Options:
shinken.webui.bottlewebui.
GunicornServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested.
shinken.webui.bottlewebui.
HTTPError
(code=500, output='Unknown Error', exception=None, traceback=None, header=None)[source]¶Bases: shinken.webui.bottlewebui.HTTPResponse
Used to generate an error page
shinken.webui.bottlewebui.
HTTPResponse
(output='', status=200, header=None)[source]¶Bases: shinken.webui.bottlewebui.BottleException
Used to break execution and immediately finish the response
shinken.webui.bottlewebui.
HTTP_CODES
= {200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 418: "I'm a teapot", 100: 'Continue', 101: 'Switching Protocols', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: '(Unused)', 307: 'Temporary Redirect', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported'}¶A dict to map HTTP status codes (e.g. 404) to phrases (e.g. ‘Not Found’)
shinken.webui.bottlewebui.
HeaderDict
(*a, **ka)[source]¶Bases: shinken.webui.bottlewebui.MultiDict
A case-insensitive version of MultiDict
that defaults to
replace the old value instead of appending it.
shinken.webui.bottlewebui.
HeaderProperty
(name, reader=None, writer=<type 'str'>, default='')[source]¶Bases: object
shinken.webui.bottlewebui.
JSONPlugin
(json_dumps=<function dumps>)[source]¶Bases: object
name
= 'json'¶shinken.webui.bottlewebui.
Jinja2Template
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlewebui.
LocalRequest
[source]¶Bases: shinken.webui.bottlewebui.BaseRequest
, thread._local
A thread-local subclass of BaseRequest
.
bind
(environ)¶Wrap a WSGI environ dictionary.
shinken.webui.bottlewebui.
LocalResponse
(body='', status=None, **headers)[source]¶Bases: shinken.webui.bottlewebui.BaseResponse
, thread._local
A thread-local subclass of BaseResponse
.
bind
(body='', status=None, **headers)¶shinken.webui.bottlewebui.
MakoTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶shinken.webui.bottlewebui.
MultiDict
(*a, **k)[source]¶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.
allitems
()¶get
(key, default=None, index=-1)[source]¶Return the current value for a key. The third index parameter defaults to -1 (last value).
items
()¶keys
()¶values
()¶shinken.webui.bottlewebui.
Request
¶alias of LocalRequest
shinken.webui.bottlewebui.
Response
¶alias of LocalResponse
shinken.webui.bottlewebui.
RocketServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested. As requested in issue 63 https://github.com/defnull/bottle/issues/#issue/63
shinken.webui.bottlewebui.
RouteBuildError
[source]¶Bases: shinken.webui.bottlewebui.RouteError
The route could not been built
shinken.webui.bottlewebui.
RouteError
[source]¶Bases: shinken.webui.bottlewebui.BottleException
This is a base class for all routing related exceptions
shinken.webui.bottlewebui.
RouteReset
[source]¶Bases: shinken.webui.bottlewebui.BottleException
If raised by a plugin or request handler, the route is reset and all plugins are re-applied.
shinken.webui.bottlewebui.
RouteSyntaxError
[source]¶Bases: shinken.webui.bottlewebui.RouteError
The route parser found something not supported by this router
shinken.webui.bottlewebui.
Router
[source]¶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). By default, wildcards consume characters up to the next slash (/). To change that, you may add a regular expression pattern (e.g. /wiki/:page#[a-z]+#).
For performance reasons, static routes (rules without wildcards) are checked first. Dynamic routes are searched in order. Try to avoid ambiguous or overlapping rules.
An optional name
parameter is used by build()
to identify
routes.
add
(rule, method, target, name=None)[source]¶Add a new route or replace the target for an existing route.
build
(_name, *anon, **args)[source]¶Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.
default
= '[^/]+'¶syntax
= <_sre.SRE_Pattern object>¶shinken.webui.bottlewebui.
ServerAdapter
(host='127.0.0.1', port=8080, **config)[source]¶Bases: object
quiet
= False¶shinken.webui.bottlewebui.
SimpleTALTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: shinken.webui.bottlewebui.BaseTemplate
Untested!
shinken.webui.bottlewebui.
SimpleTemplate
(source=None, name=None, lookup=[], encoding='utf8', **settings)[source]¶Bases: shinken.webui.bottlewebui.BaseTemplate
blocks
= ('if', 'elif', 'else', 'try', 'except', 'finally', 'for', 'while', 'with', 'def', 'class')¶dedent_blocks
= ('elif', 'else', 'except', 'finally')¶re_pytokens
= <_sre.SRE_Pattern object at 0x4d0db10>¶shinken.webui.bottlewebui.
TemplatePlugin
[source]¶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.
name
= 'template'¶shinken.webui.bottlewebui.
TornadoServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
The super hyped asynchronous server by facebook. Untested.
shinken.webui.bottlewebui.
TwistedServer
(host='127.0.0.1', port=8080, **config)[source]¶Bases: shinken.webui.bottlewebui.ServerAdapter
Untested.
shinken.webui.bottlewebui.
WSGIHeaderDict
(environ)[source]¶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.)
shinken.webui.bottlewebui.
abort
(code=500, text='Unknown Error: Application stopped.')[source]¶Aborts execution and causes a HTTP error.
shinken.webui.bottlewebui.
auth_basic
(check, realm='private', text='Access denied')[source]¶Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
shinken.webui.bottlewebui.
cached_property
(func)[source]¶A property that, if accessed, replaces itself with the computed value. Subsequent accesses won’t call the getter again.
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.
shinken.webui.bottlewebui.
debug
(mode=True)[source]¶Change the debug level. There is only one debug level supported at the moment.
shinken.webui.bottlewebui.
error
(*a, **ka)¶Decorator: Register an output handler for a HTTP error code
shinken.webui.bottlewebui.
ext
= <module 'shinken.webui.bottlewebui.ext' from '<virtual>'>¶A virtual package that redirects import statements.
Example: import bottle.ext.sqlite
actually imports bottle_sqlite.
shinken.webui.bottlewebui.
hook
(*a, **ka)¶Return a decorator that attaches a callback to a hook.
shinken.webui.bottlewebui.
install
(*a, **ka)¶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.
shinken.webui.bottlewebui.
lazy_attribute
(func)[source]¶Bases: object
A property that caches itself to the class object.
shinken.webui.bottlewebui.
load_app
(target)[source]¶Load a bottle application based on a target string and return the application object.
If the target is an import path (e.g. package.module), the application stack is used to isolate the routes defined in that module. If the target contains a colon (e.g. package.module:myapp) the module variable specified after the colon is returned instead.
shinken.webui.bottlewebui.
local
= <thread._local object>¶A thread-save namespace. Not used by Bottle.
shinken.webui.bottlewebui.
make_default_app_wrapper
(name)[source]¶Return a callable that relays calls to the current default app.
shinken.webui.bottlewebui.
mount
(*a, **ka)¶Mount an application to a specific URL prefix. The prefix is added
to SCIPT_PATH and removed from PATH_INFO before the sub-application
is called.:param app: an instance of Bottle
.:param prefix:
path prefix used as a mount-point.
All other parameters are passed to the underlying route()
call.
shinken.webui.bottlewebui.
parse_auth
(header)[source]¶Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
shinken.webui.bottlewebui.
parse_date
(ims)[source]¶Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
shinken.webui.bottlewebui.
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.:param script_name: The SCRIPT_NAME path.:param script_name: |
---|
The PATH_INFO path.:param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
shinken.webui.bottlewebui.
redirect
(url, code=303)[source]¶Aborts execution and causes a 303 redirect.
shinken.webui.bottlewebui.
request
= <shinken.webui.bottlewebui.LocalRequest object>¶A thread-save instance of Request
representing the current request.
shinken.webui.bottlewebui.
response
= <shinken.webui.bottlewebui.LocalResponse object>¶A thread-save instance of Response
used to build the HTTP response.
shinken.webui.bottlewebui.
route
(*a, **ka)¶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.:param 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.:param method: HTTP method (GET, POST, PUT, ...)
or a list of methods to listen to. (default: GET):param callback: An optional
shortcut to avoid the decorator syntax. route(..., callback=func)
equals
route(...)(func)
:param name: The name for this route. (default: None):param apply:
A decorator or plugin or a list of plugins. These are applied to the route callback in
addition to installed plugins.:param 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()
).
shinken.webui.bottlewebui.
run
(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs)[source]¶Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
load_app()
. (default: default_app()
):param server:
Server adapter to use. See server_names
keys
for valid names or pass a ServerAdapter
subclass.
(default: wsgiref):param 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):param port: Server port to
bind to. Values below 1024 require root privileges. (default: 8080):param reloader:
Start auto-reloading server? (default: False):param interval: Auto-reloader interval
in seconds (default: 1):param quiet: Suppress output to stdout and stderr?
(default: False):param options: Options passed to the server adapter.
shinken.webui.bottlewebui.
static_file
(filename, root, mimetype='auto', download=False)[source]¶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.
shinken.webui.bottlewebui.
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).
shinken.webui.bottlewebui.
tonat
(data, enc='utf8')¶Convert anything to native strings
shinken.webui.bottlewebui.
uninstall
(*a, **ka)¶Uninstall plugins. Pass an instance to remove a specific plugin.
Pass a type object to remove all plugins that match that type.
Subclasses are not removed. Pass a string to remove all plugins with
a matching name
attribute. Pass True
to remove all plugins.
The list of affected plugins is returned.
shinken.webui.bottlewebui.
url
(*a, **ka)¶Return a string that matches a named route
shinken.webui.bottlewebui.
validate
(**vkargs)[source]¶Validates and manipulates keyword arguments by user defined callables. Handles ValueError and missing arguments by raising HTTPError(403).
shinken.webui.bottlewebui.
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.
shinken.webui.bottlewebui.
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'