arelle.webserver.bottle#

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) 2009-2018, Marcel Hellkamp. License: MIT (see LICENSE for details)

Module Contents#

Classes#

DictProperty

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

cached_property

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

lazy_attribute

A property that caches itself to the class object.

Router

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.

Route

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

Bottle

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

BaseRequest

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

HeaderProperty

BaseResponse

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

LocalRequest

A thread-local subclass of :class:BaseRequest with a different set of attributes for each thread. There is usually only one global instance of this class (:data:request). If accessed during a request/response cycle, this instance always refers to the current request (even on a multithreaded server).

LocalResponse

A thread-local subclass of :class:BaseResponse with a different set of attributes for each thread. There is usually only one global instance of this class (:data:response). Its attributes are used to build the HTTP response at the end of the request/response cycle.

JSONPlugin

TemplatePlugin

This plugin applies the :func: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.

_ImportRedirect

MultiDict

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.

FormsDict

This :class: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 :attr:input_encoding (default: ‘utf8’). Missing attributes default to an empty string.

HeaderDict

A case-insensitive version of :class:MultiDict that defaults to replace the old value instead of appending it.

WSGIHeaderDict

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.

ConfigDict

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

AppStack

A stack-like list. Calling it returns the head of the stack.

WSGIFileWrapper

_closeiter

This only exists to be able to attach a .close method to iterators that do not support attribute assignment (most of itertools).

ResourceManager

This class manages a list of search paths and helps to find and open application-bound resources (files).

FileUpload

ServerAdapter

CGIServer

FlupFCGIServer

WSGIRefServer

CherryPyServer

CherootServer

WaitressServer

PasteServer

MeinheldServer

FapwsServer

Extremely fast webserver using libev. See http://www.fapws.org/

TornadoServer

The super hyped asynchronous server by facebook. Untested.

AppEngineServer

Adapter for Google App Engine.

TwistedServer

Untested.

DieselServer

Untested.

GeventServer

Untested. Options:

GunicornServer

Untested. See http://gunicorn.org/configure.html for options.

EventletServer

Untested. Options:

BjoernServer

Fast server written in C: https://github.com/jonashaag/bjoern

AsyncioServerAdapter

Extend ServerAdapter for adding custom event loop

AiohttpServer

Asynchronous HTTP client/server framework for asyncio https://pypi.python.org/pypi/aiohttp/ https://pypi.org/project/aiohttp-wsgi/

AiohttpUVLoopServer

uvloop https://github.com/MagicStack/uvloop

AutoServer

Untested.

FileCheckerThread

Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets too old.

BaseTemplate

Base class and minimal API for template adapters

MakoTemplate

CheetahTemplate

Jinja2Template

SimpleTemplate

StplParser

Parser for stpl templates.

Functions#

_cli_parse

_cli_patch

tob

touni

_stderr

update_wrapper

depr

makelist

_re_flatten

Turn all capturing groups in a regular expression pattern into non-capturing groups.

_hkey

_hval

_local_property

abort

Aborts execution and causes a HTTP error.

redirect

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

_file_iter_range

Yield chunks from a range in a file, optionally closing it at the end. No chunk is bigger than maxread.

static_file

Open a file in a safe way and return an instance of :exc:HTTPResponse that can be sent back to the client.

debug

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

http_date

parse_date

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

parse_auth

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

parse_range_header

Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.

_parse_http_header

Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results.

_parse_qsl

_lscmp

Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.

cookie_encode

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

cookie_decode

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

cookie_is_encoded

Return True if the argument looks like a encoded cookie.

html_escape

Escape HTML special characters &<> and quotes '".

html_quote

Escape and quote a string to be used as an HTTP attribute.

yieldroutes

Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example::

path_shift

Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

auth_basic

Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=…) parameter.

make_default_app_wrapper

Return a callable that relays calls to the current default app.

load

Import a module or fetch an object from a module.

load_app

Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:load for the target parameter.

run

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

template

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

view

Decorator: renders a template for a handler. The handler can control its behavior like that:

_main

Data#

API#

arelle.webserver.bottle.__author__#

‘Marcel Hellkamp’

arelle.webserver.bottle.__version__#

‘0.13-dev’

arelle.webserver.bottle.__license__#

‘MIT’

arelle.webserver.bottle._cli_parse(args)#
arelle.webserver.bottle._cli_patch(cli_args)#
arelle.webserver.bottle.py#

None

arelle.webserver.bottle.py3k#

None

arelle.webserver.bottle.tob(s, enc='utf8')#
arelle.webserver.bottle.touni(s, enc='utf8', err='strict')#
arelle.webserver.bottle.tonat#

None

arelle.webserver.bottle._stderr(*args)#
arelle.webserver.bottle.update_wrapper(wrapper, wrapped, *a, **ka)#
arelle.webserver.bottle.depr(major, minor, cause, fix)#
arelle.webserver.bottle.makelist(data)#
class arelle.webserver.bottle.DictProperty(attr, key=None, read_only=False)#

Bases: object

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

Initialization

__call__(func)#
__get__(obj, cls)#
__set__(obj, value)#
__delete__(obj)#
class arelle.webserver.bottle.cached_property(func)#

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.

Initialization

__get__(obj, cls)#
class arelle.webserver.bottle.lazy_attribute(func)#

Bases: object

A property that caches itself to the class object.

Initialization

__get__(obj, cls)#
exception arelle.webserver.bottle.BottleException#

Bases: Exception

A base class for exceptions used by bottle.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception arelle.webserver.bottle.RouteError#

Bases: arelle.webserver.bottle.BottleException

This is a base class for all routing related exceptions

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception arelle.webserver.bottle.RouteReset#

Bases: arelle.webserver.bottle.BottleException

If raised by a plugin or request handler, the route is reset and all plugins are re-applied.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception arelle.webserver.bottle.RouterUnknownModeError#

Bases: arelle.webserver.bottle.RouteError

exception arelle.webserver.bottle.RouteSyntaxError#

Bases: arelle.webserver.bottle.RouteError

The route parser found something not supported by this router.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception arelle.webserver.bottle.RouteBuildError#

Bases: arelle.webserver.bottle.RouteError

The route could not be built.

Initialization

Initialize self. See help(type(self)) for accurate signature.

arelle.webserver.bottle._re_flatten(p)#

Turn all capturing groups in a regular expression pattern into non-capturing groups.

class arelle.webserver.bottle.Router(strict=False)#

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.

Initialization

default_pattern#

‘[^/]+’

default_filter#

‘re’

_MAX_GROUPS_PER_PATTERN#

99

add_filter(name, func)#

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.

rule_syntax#

‘compile(…)’

_itertokens(rule)#
add(rule, method, target, name=None)#

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

_compile(method)#
build(_name, *anons, **query)#

Build an URL by filling the wildcards in a rule.

match(environ)#

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

class arelle.webserver.bottle.Route(app, rule, method, callback, name=None, plugins=None, skiplist=None, **config)#

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 turning an URL path rule into a regular expression usable by the Router.

Initialization

call()#

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

reset()#

Forget any cached values. The next time :attr:call is accessed, all plugins are re-applied.

prepare()#

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

all_plugins()#

Yield all Plugins affecting this route.

_make_callback()#
get_undecorated_callback()#

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

get_callback_args()#

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

get_config(key, default=None)#

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

__repr__()#
class arelle.webserver.bottle.Bottle(**kwargs)#

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.

Initialization

_global_config()#
catchall#

‘DictProperty(…)’

__hook_names#

(‘before_request’, ‘after_request’, ‘app_reset’, ‘config’)

__hook_reversed#

None

_hooks()#
add_hook(name, func)#

Attach a callback to a hook. Three hooks are currently implemented:

before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of its outcome. app_reset Called whenever :meth:Bottle.reset is called.

remove_hook(name, func)#

Remove a callback from a hook.

trigger_hook(__name, *args, **kwargs)#

Trigger a hook and return a list of results.

hook(name)#

Return a decorator that attaches a callback to a hook. See

Meth:

add_hook for details.

_mount_wsgi(prefix, app, **options)#
_mount_app(prefix, app, **options)#
mount(prefix, app, **options)#

Mount an application (:class:Bottle or plain WSGI) to a specific URL prefix. Example::

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

  • app – an instance of :class:Bottle or a WSGI application.

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

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

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

merge(routes)#

Merge the routes of another :class:Bottle application or a list of

Class:

Route objects into this application. The routes keep their ‘owner’, meaning that the :data:Route.app attribute is not changed.

install(plugin)#

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 :class:Plugin API.

uninstall(plugin)#

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.

reset(route=None)#

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.

close()#

Close the application and all installed plugins.

run(**kwargs)#

Calls :func:run with the same parameters.

match(environ)#

Search for a matching route and return a (:class:Route, urlargs) tuple. The second value is a dictionary with parameters extracted from the URL. Raise :exc:HTTPError (404/405) on a non-match.

get_url(routename, **kargs)#

Return a string that matches a named route

add_route(route)#

Add a route object, but do not change the :data:Route.app attribute.

route(path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config) Any#

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 :class:Router 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) equals route(...)(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 :meth:Plugin.apply).

get(path=None, method='GET', **options)#

Equals :meth:route.

post(path=None, method='POST', **options)#

Equals :meth:route with a POST method parameter.

put(path=None, method='PUT', **options)#

Equals :meth:route with a PUT method parameter.

delete(path=None, method='DELETE', **options)#

Equals :meth:route with a DELETE method parameter.

patch(path=None, method='PATCH', **options)#

Equals :meth:route with a PATCH method parameter.

error(code=500, callback=None)#

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

def error_handler_500(error):
    return 'error_handler_500'

app.error(code=500, callback=error_handler_500)

@app.error(404)
def error_handler_404(error):
    return 'error_handler_404'
default_error_handler(res)#
_handle(environ)#
_cast(out, peek=None)#

Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes

wsgi(environ, start_response)#

The bottle WSGI-interface.

__call__(environ, start_response)#

Each instance of :class:’Bottle’ is a WSGI application.

__enter__()#

Use this application as default for all module-level shortcuts.

__exit__(exc_type, exc_value, traceback)#
__setattr__(name, value)#
class arelle.webserver.bottle.BaseRequest(environ=None)#

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.’). This is the recommended way to store and access request-specific data.

Initialization

Wrap a WSGI environ dictionary.

__slots__#

(‘environ’,)

MEMFILE_MAX#

102400

app()#

Bottle application handling this request.

route()#

The bottle :class:Route object that matches this request.

url_args()#

The arguments extracted from the URL.

property path#

The value of PATH_INFO with exactly one prefixed slash (to fix broken clients and avoid the “empty path” edge case).

property method#

The REQUEST_METHOD value as an uppercase string.

headers()#

A :class:WSGIHeaderDict that provides case-insensitive access to HTTP request headers.

get_header(name, default=None) str | None#

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

cookies()#

Cookies parsed into a :class:FormsDict. Signed cookies are NOT decoded. Use :meth:get_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

Meth:

BaseResponse.set_cookie). If anything goes wrong (missing cookie or wrong signature), return a default value.

query()#

The :attr:query_string parsed into a :class: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

Class:

Router.

forms()#

Form values parsed from an url-encoded or multipart/form-data encoded POST or PUT request body. The result is returned as a

Class:

FormsDict. All keys and values are strings. File uploads are stored separately in :attr:files.

params()#

A :class:FormsDict with the combined values of :attr:query and

Attr:

forms. File uploads are stored in :attr:files.

files()#

File uploads parsed from multipart/form-data encoded POST or PUT request body. The values are instances of :class:FileUpload.

json()#

If the Content-Type header is application/json or application/json-rpc, this property holds the parsed content of the request body. Only requests smaller than :attr:MEMFILE_MAX are processed to avoid memory exhaustion. Invalid JSON raises a 400 error response.

_iter_body(read, bufsize)#
static _iter_chunked(read, bufsize)#
_body()#
_get_body_string(maxread)#

Read body into a string. Raise HTTPError(413) on requests that are to large.

property body#

The HTTP request body as a seek-able file-like object. Depending on

Attr:

MEMFILE_MAX, this is either a temporary file or a

Class:

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.

property chunked#

True if Chunked transfer encoding was.

GET#

None

POST()#

The values of :attr:forms and :attr:files combined into a single

Class:

FormsDict. Values are either strings (form values) or instances of :class:cgi.FieldStorage (file uploads).

property 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()#

The :attr:url string as an :class: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.

property fullpath#

Request path including :attr:script_name (if present).

property query_string#

The raw :attr:query part of the URL (everything in between ? and #) as a string.

property 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)#

Shift path segments from :attr:path to :attr:script_name and vice versa.

Parameters:

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

property 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, :attr:body will be empty.

property content_type#

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

property 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).

property is_ajax#

Alias for :attr:is_xhr. “Ajax” is not the right term.

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

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

property remote_addr#

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

copy()#

Return a new :class:Request with a shallow :attr:environ copy.

get(value, default=None)#
__getitem__(key)#
__delitem__(key)#
__iter__()#
__len__()#
keys()#
__setitem__(key, value)#

Change an environ value and clear all caches that depend on it.

__repr__()#
__getattr__(name)#

Search in self.environ for additional user defined attributes.

__setattr__(name, value)#
__delattr__(name)#
arelle.webserver.bottle._hkey(key)#
arelle.webserver.bottle._hval(value)#
class arelle.webserver.bottle.HeaderProperty(name, reader=None, writer=None, default='')#

Bases: object

Initialization

__get__(obj, _)#
__set__(obj, value)#
__delete__(obj)#
class arelle.webserver.bottle.BaseResponse(body='', status=None, headers=None, **more_headers)#

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.

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

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

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

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

Initialization

default_status#

200

default_content_type#

‘text/html; charset=UTF-8’

bad_headers#

None

copy(cls=None)#

Returns a copy of self.

__iter__()#
close()#
property status_line#

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

property status_code#

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

_set_status(status)#
_get_status()#
status#

‘property(…)’

property headers#

An instance of :class:HeaderDict, a case-insensitive dict-like view on the response headers.

__contains__(name)#
__delitem__(name)#
__getitem__(name)#
__setitem__(name, value)#
get_header(name, default=None)#

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

set_header(name, value)#

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

add_header(name, value)#

Add an additional response header, not removing duplicates.

iter_headers()#

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

_wsgi_status_line()#

WSGI conform status line (latin1-encodeable)

property headerlist#

WSGI conform list of (header, value) tuples.

content_type#

‘HeaderProperty(…)’

content_length#

‘HeaderProperty(…)’

expires#

‘HeaderProperty(…)’

property charset#

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

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 :class:cookie.Morsel, including:

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

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

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

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

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

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

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

If neither expires nor maxage 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: Pickle is a potentially dangerous format. If an attacker gains access to the secret key, he could forge cookies that execute code on server side if unpickled. Using pickle is discouraged and support for it will be removed in later versions of bottle.

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.

__repr__()#
arelle.webserver.bottle._local_property()#
class arelle.webserver.bottle.LocalRequest(environ=None)#

Bases: arelle.webserver.bottle.BaseRequest

A thread-local subclass of :class:BaseRequest with a different set of attributes for each thread. There is usually only one global instance of this class (:data:request). If accessed during a request/response cycle, this instance always refers to the current request (even on a multithreaded server).

Initialization

Wrap a WSGI environ dictionary.

bind#

None

environ#

‘_local_property(…)’

class arelle.webserver.bottle.LocalResponse(body='', status=None, headers=None, **more_headers)#

Bases: arelle.webserver.bottle.BaseResponse

A thread-local subclass of :class:BaseResponse with a different set of attributes for each thread. There is usually only one global instance of this class (:data:response). Its attributes are used to build the HTTP response at the end of the request/response cycle.

Initialization

bind#

None

_status_line#

‘_local_property(…)’

_status_code#

‘_local_property(…)’

_cookies#

‘_local_property(…)’

_headers#

‘_local_property(…)’

body#

‘_local_property(…)’

arelle.webserver.bottle.Request#

None

arelle.webserver.bottle.Response#

None

exception arelle.webserver.bottle.HTTPResponse(body='', status=None, headers=None, **more_headers)#

Bases: arelle.webserver.bottle.Response, arelle.webserver.bottle.BottleException

apply(other)#
exception arelle.webserver.bottle.HTTPError(status=None, body=None, exception=None, traceback=None, **more_headers)#

Bases: arelle.webserver.bottle.HTTPResponse

default_status#

500

exception arelle.webserver.bottle.PluginError#

Bases: arelle.webserver.bottle.BottleException

class arelle.webserver.bottle.JSONPlugin(json_dumps=json_dumps)#

Bases: object

Initialization

name#

‘json’

api#

2

setup(app)#
apply(callback, route)#
class arelle.webserver.bottle.TemplatePlugin#

Bases: object

This plugin applies the :func: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’

api#

2

setup(app)#
apply(callback, route)#
class arelle.webserver.bottle._ImportRedirect(name, impmask)#

Bases: object

Initialization

Create a virtual package that redirects imports (see PEP 302).

find_module(fullname, path=None)#
load_module(fullname)#
class arelle.webserver.bottle.MultiDict(*a, **k)#

Bases: collections.abc.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.

Initialization

__len__()#
__iter__()#
__contains__(key)#
__delitem__(key)#
__getitem__(key)#
__setitem__(key, value)#
keys()#
get(key, default=None, index=-1, type=None)#

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.

append(key, value)#

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

replace(key, value)#

Replace the list of values with a single value.

getall(key)#

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

getone#

None

getlist#

None

class arelle.webserver.bottle.FormsDict(*a, **k)#

Bases: arelle.webserver.bottle.MultiDict

This :class: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 :attr:input_encoding (default: ‘utf8’). Missing attributes default to an empty string.

Initialization

input_encoding#

‘utf8’

recode_unicode#

True

_fix(s, encoding=None)#
decode(encoding=None)#

Returns a copy with all keys and values de- or recoded to match

Attr:

input_encoding. Some libraries (e.g. WTForms) want a unicode dictionary.

getunicode(name, default=None, encoding=None)#

Return the value as a unicode string, or the default.

__getattr__(name, default=unicode())#
class arelle.webserver.bottle.HeaderDict(*a, **ka)#

Bases: arelle.webserver.bottle.MultiDict

A case-insensitive version of :class:MultiDict that defaults to replace the old value instead of appending it.

Initialization

__contains__(key)#
__delitem__(key)#
__getitem__(key)#
__setitem__(key, value)#
append(key, value)#
replace(key, value)#
getall(key)#
get(key, default=None, index=-1)#
filter(names)#
class arelle.webserver.bottle.WSGIHeaderDict(environ)#

Bases: collections.abc.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.)

Initialization

cgikeys#

(‘CONTENT_TYPE’, ‘CONTENT_LENGTH’)

_ekey(key)#

Translate header field name to CGI/WSGI environ key.

raw(key, default=None)#

Return the header value as is (may be bytes or unicode).

__getitem__(key)#
__setitem__(key, value)#
__delitem__(key)#
__iter__()#
keys()#
__len__()#
__contains__(key)#
arelle.webserver.bottle._UNSET#

‘object(…)’

class arelle.webserver.bottle.ConfigDict#

Bases: dict

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

This dict-like class is heavily optimized for read access. All read-only methods as well as item access should be as fast as the built-in dict.

Initialization

Initialize self. See help(type(self)) for accurate signature.

__slots__#

(‘_meta’, ‘_change_listener’, ‘_overlays’, ‘_virtual_keys’, ‘_source’, ‘weakref’)

load_module(path, squash=True)#

Load values from a Python module.

Example modue config.py::

 DEBUG = True
 SQLITE = {
     "db": ":memory:"
 }

c = ConfigDict() c.load_module(‘config’) {DEBUG: True, ‘SQLITE.DB’: ‘memory’} c.load_module(“config”, False) {‘DEBUG’: True, ‘SQLITE’: {‘DB’: ‘memory’}}

Parameters:

squash – If true (default), dictionary values are assumed to represent namespaces (see :meth:load_dict).

load_config(filename, **options)#

Load values from an *.ini style config file.

A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by either = or :. Section names and keys are case-insensitive. Leading and trailing whitespace is removed from keys and values. Values can be omitted, in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Commands are prefixed by # or ; and may only appear on their own on an otherwise empty line.

Both section and key names may contain dots (.) as namespace separators. The actual configuration parameter name is constructed by joining section name and key name together and converting to lower case.

The special sections bottle and ROOT refer to the root namespace and the DEFAULT section defines default values for all other sections.

With Python 3, extended string interpolation is enabled.

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

  • options

    All keyword parameters are passed to the underlying

    class:

    python:configparser.ConfigParser constructor call.

load_dict(source, namespace='')#

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

c = ConfigDict() c.load_dict({‘some’: {‘namespace’: {‘key’: ‘value’} } }) {‘some.namespace.key’: ‘value’}

update(*a, **ka)#

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

c = ConfigDict() c.update(‘some.namespace’, key=’value’)

setdefault(key, value)#
__setitem__(key, value)#
__delitem__(key)#
_set_virtual(key, value)#

Recursively set or update virtual keys. Do nothing if non-virtual value is present.

_delete_virtual(key)#

Recursively delete virtual entry. Do nothing if key is not virtual.

_on_change(key, value)#
_add_change_listener(func)#
meta_get(key, metafield, default=None)#

Return the value of a meta field for a key.

meta_set(key, metafield, value)#

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

meta_list(key)#

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

_define(key, default=_UNSET, help=_UNSET, validate=_UNSET)#

(Unstable) Shortcut for plugins to define own config parameters.

_iter_overlays()#
_make_overlay()#

(Unstable) Create a new overlay that acts like a chained map: Values missing in the overlay are copied from the source map. Both maps share the same meta entries.

Entries that were copied from the source are called ‘virtual’. You can not delete virtual keys, but overwrite them, which turns them into non-virtual entries. Setting keys on an overlay never affects its source, but may affect any number of child overlays.

Other than collections.ChainMap or most other implementations, this approach does not resolve missing keys on demand, but instead actively copies all values from the source to the overlay and keeps track of virtual and non-virtual keys internally. This removes any lookup-overhead. Read-access is as fast as a build-in dict for both virtual and non-virtual keys.

Changes are propagated recursively and depth-first. A failing on-change handler in an overlay stops the propagation of virtual values and may result in an partly updated tree. Take extra care here and make sure that on-change handlers never fail.

Used by Route.config

class arelle.webserver.bottle.AppStack#

Bases: list

A stack-like list. Calling it returns the head of the stack.

Initialization

Initialize self. See help(type(self)) for accurate signature.

__call__()#

Return the current default application.

push(value=None)#

Add a new :class:Bottle instance to the stack

new_app#

None

property default#
class arelle.webserver.bottle.WSGIFileWrapper(fp, buffer_size=1024 * 64)#

Bases: object

Initialization

__iter__()#
class arelle.webserver.bottle._closeiter(iterator, close=None)#

Bases: object

This only exists to be able to attach a .close method to iterators that do not support attribute assignment (most of itertools).

Initialization

__iter__()#
close()#
class arelle.webserver.bottle.ResourceManager(base='./', opener=open, cachemode='all')#

Bases: object

This class manages a list of search paths and helps to find and open application-bound resources (files).

Parameters:
  • base – default value for :meth:add_path calls.

  • opener – callable used to open resources.

  • cachemode – controls which lookups are cached. One of ‘all’, ‘found’ or ‘none’.

Initialization

add_path(path, base=None, index=None, create=False)#

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 :attr:base which defaults to os.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__)
__iter__()#

Iterate over all existing files in all registered paths.

lookup(name)#

Search for a resource and return an absolute file path, or None.

The :attr:path list is searched in order. The first match is returned. Symlinks are followed. The result is cached to speed up future lookups.

open(name, mode='r', *args, **kwargs)#

Find a resource and return a file object, or raise IOError.

class arelle.webserver.bottle.FileUpload(fileobj, name, filename, headers=None)#

Bases: object

Initialization

Wrapper for file uploads.

content_type#

‘HeaderProperty(…)’

content_length#

‘HeaderProperty(…)’

get_header(name, default=None)#

Return the value of a header within the multipart part.

filename()#

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

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

_copy_file(fp, chunk_size=2**16)#
save(destination, overwrite=False, chunk_size=2**16)#

Save file to disk or copy its content to an open file(-like) object. If destination is a directory, :attr:filename is added to the path. Existing files are not overwritten by default (IOError).

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

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

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

arelle.webserver.bottle.abort(code=500, text='Unknown Error.')#

Aborts execution and causes a HTTP error.

arelle.webserver.bottle.redirect(url, code=None)#

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

arelle.webserver.bottle._file_iter_range(fp, offset, bytes, maxread=1024 * 1024, close=False)#

Yield chunks from a range in a file, optionally closing it at the end. No chunk is bigger than maxread.

arelle.webserver.bottle.static_file(filename, root, mimetype=True, download=False, charset='UTF-8', etag=None, headers=None) arelle.webserver.bottle.HTTPResponse#

Open a file in a safe way and return an instance of :exc:HTTPResponse that can be sent back to the client.

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

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

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

  • download – If True, ask the browser to open a Save as... dialog instead of opening the file with the associated program. You can specify a custom filename as a string. If not specified, the original filename is used (default: False).

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

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

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

While checking user input is always a good idea, this function provides additional protection against malicious filename parameters from breaking out of the root directory and leaking sensitive information to an attacker.

Read-protected files or files outside of the root directory are answered with 403 Access Denied. Missing files result in a 404 Not Found response. Conditional requests (If-Modified-Since, If-None-Match) are answered with 304 Not Modified whenever possible. HEAD and Range requests (used by download managers to check or continue partial downloads) are also handled automatically.

arelle.webserver.bottle.debug(mode=True)#

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

arelle.webserver.bottle.http_date(value)#
arelle.webserver.bottle.parse_date(ims)#

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

arelle.webserver.bottle.parse_auth(header)#

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

arelle.webserver.bottle.parse_range_header(header, maxlen=0)#

Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.

arelle.webserver.bottle._hsplit#

None

arelle.webserver.bottle._parse_http_header(h)#

Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results.

Parameters:

h – A header string (e.g. text/html,text/plain;q=0.9,*/*;q=0.8)

Returns:

List of (value, params) tuples. The second element is a (possibly empty) dict.

arelle.webserver.bottle._parse_qsl(qs)#
arelle.webserver.bottle._lscmp(a, b)#

Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.

arelle.webserver.bottle.cookie_encode(data, key, digestmod=None)#

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

arelle.webserver.bottle.cookie_decode(data, key, digestmod=None)#

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

arelle.webserver.bottle.cookie_is_encoded(data)#

Return True if the argument looks like a encoded cookie.

arelle.webserver.bottle.html_escape(string)#

Escape HTML special characters &<> and quotes '".

arelle.webserver.bottle.html_quote(string)#

Escape and quote a string to be used as an HTTP attribute.

arelle.webserver.bottle.yieldroutes(func)#

Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example::

a()         -> '/a'
b(x, y)     -> '/b/<x>/<y>'
c(x, y=5)   -> '/c/<x>' and '/c/<x>/<y>'
d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
arelle.webserver.bottle.path_shift(script_name, path_info, shift=1)#

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)

arelle.webserver.bottle.auth_basic(check, realm='private', text='Access denied')#

Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=…) parameter.

arelle.webserver.bottle.make_default_app_wrapper(name)#

Return a callable that relays calls to the current default app.

arelle.webserver.bottle.route#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.get#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.post#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.put#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.delete#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.patch#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.error#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.mount#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.hook#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.install#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.uninstall#

‘make_default_app_wrapper(…)’

arelle.webserver.bottle.url#

‘make_default_app_wrapper(…)’

class arelle.webserver.bottle.ServerAdapter(host='127.0.0.1', port=8080, **options)#

Bases: object

Initialization

quiet#

False

run(handler)#
__repr__()#
class arelle.webserver.bottle.CGIServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

quiet#

True

run(handler)#
class arelle.webserver.bottle.FlupFCGIServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.WSGIRefServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(app)#
class arelle.webserver.bottle.CherryPyServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.CherootServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.WaitressServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.PasteServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.MeinheldServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Initialization

run(handler)#
class arelle.webserver.bottle.FapwsServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Extremely fast webserver using libev. See http://www.fapws.org/

Initialization

run(handler)#
class arelle.webserver.bottle.TornadoServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

The super hyped asynchronous server by facebook. Untested.

Initialization

run(handler)#
class arelle.webserver.bottle.AppEngineServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Adapter for Google App Engine.

Initialization

quiet#

True

run(handler)#
class arelle.webserver.bottle.TwistedServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested.

Initialization

run(handler)#
class arelle.webserver.bottle.DieselServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested.

Initialization

run(handler)#
class arelle.webserver.bottle.GeventServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested. Options:

  • See gevent.wsgi.WSGIServer() documentation for more options.

Initialization

run(handler)#
class arelle.webserver.bottle.GunicornServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested. See http://gunicorn.org/configure.html for options.

Initialization

run(handler)#
class arelle.webserver.bottle.EventletServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested. Options:

  • backlog adjust the eventlet backlog parameter which is the maximum number of queued connections. Should be at least 1; the maximum value is system-dependent.

  • family: (default is 2) socket family, optional. See socket documentation for available families.

Initialization

run(handler)#
class arelle.webserver.bottle.BjoernServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Fast server written in C: https://github.com/jonashaag/bjoern

Initialization

run(handler)#
class arelle.webserver.bottle.AsyncioServerAdapter(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Extend ServerAdapter for adding custom event loop

Initialization

get_event_loop()#
class arelle.webserver.bottle.AiohttpServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.AsyncioServerAdapter

Asynchronous HTTP client/server framework for asyncio https://pypi.python.org/pypi/aiohttp/ https://pypi.org/project/aiohttp-wsgi/

Initialization

get_event_loop()#
run(handler)#
class arelle.webserver.bottle.AiohttpUVLoopServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.AiohttpServer

uvloop https://github.com/MagicStack/uvloop

Initialization

get_event_loop()#
class arelle.webserver.bottle.AutoServer(host='127.0.0.1', port=8080, **options)#

Bases: arelle.webserver.bottle.ServerAdapter

Untested.

Initialization

adapters#

None

run(handler)#
arelle.webserver.bottle.server_names#

None

arelle.webserver.bottle.load(target, **namespace)#

Import a module or fetch an object from a module.

  • package.module returns module as a module object.

  • pack.mod:name returns the module variable name from pack.mod.

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

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

arelle.webserver.bottle.load_app(target)#

Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:load for the target parameter.

arelle.webserver.bottle._debug#

None

arelle.webserver.bottle.run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, config=None, **kargs)#

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

Parameters:
  • app

    WSGI application or target string supported by

    func:

    load_app. (default: :func:default_app)

  • server – Server adapter to use. See :data:server_names keys for valid names or pass a :class:ServerAdapter 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.

class arelle.webserver.bottle.FileCheckerThread(lockfile, interval)#

Bases: threading.Thread

Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets too old.

Initialization

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is a list or tuple of arguments for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.init()) before doing anything else to the thread.

run()#
__enter__()#
__exit__(exc_type, *_)#
exception arelle.webserver.bottle.TemplateError#

Bases: arelle.webserver.bottle.BottleException

class arelle.webserver.bottle.BaseTemplate(source=None, name=None, lookup=None, encoding='utf8', **settings)#

Bases: object

Base class and minimal API for template adapters

Initialization

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.

extensions#

[‘tpl’, ‘html’, ‘thtml’, ‘stpl’]

settings#

None

defaults#

None

classmethod search(name, lookup=None)#

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

classmethod global_config(key, *args)#

This reads or sets the global settings stored in class.settings.

abstract prepare(**options)#

Run preparations (parsing, caching, …). It should be possible to call this again to refresh a template or to update settings.

abstract render(*args, **kwargs)#

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

class arelle.webserver.bottle.MakoTemplate(source=None, name=None, lookup=None, encoding='utf8', **settings)#

Bases: arelle.webserver.bottle.BaseTemplate

prepare(**options)#
render(*args, **kwargs)#
class arelle.webserver.bottle.CheetahTemplate(source=None, name=None, lookup=None, encoding='utf8', **settings)#

Bases: arelle.webserver.bottle.BaseTemplate

prepare(**options)#
render(*args, **kwargs)#
class arelle.webserver.bottle.Jinja2Template(source=None, name=None, lookup=None, encoding='utf8', **settings)#

Bases: arelle.webserver.bottle.BaseTemplate

prepare(filters=None, tests=None, globals={}, **kwargs)#
render(*args, **kwargs)#
loader(name)#
class arelle.webserver.bottle.SimpleTemplate(source=None, name=None, lookup=None, encoding='utf8', **settings)#

Bases: arelle.webserver.bottle.BaseTemplate

prepare(escape_func=html_escape, noescape=False, syntax=None, **ka)#
co()#
code()#
_rebase(_env, _name=None, **kwargs)#
_include(_env, _name=None, **kwargs)#
execute(_stdout, kwargs)#
render(*args, **kwargs)#

Render the template using keyword arguments as local variables.

exception arelle.webserver.bottle.StplSyntaxError#

Bases: arelle.webserver.bottle.TemplateError

class arelle.webserver.bottle.StplParser(source, syntax=None, encoding='utf8')#

Bases: object

Parser for stpl templates.

Initialization

_re_cache#

None

_re_tok = <Multiline-String>#
_re_inl#

‘replace(…)’

_re_split#

‘(?m)^[ \t]*(\?)((%(line_start)s)|(%(block_start)s))’

default_syntax#

‘<% %> % {{ }}’

get_syntax()#

Tokens as a space separated string (default: <% %> % {{ }})

set_syntax(syntax)#
syntax#

‘property(…)’

translate()#
read_code(pysource, multiline)#
flush_text()#
static process_inline(chunk)#
write_code(line, comment='')#
arelle.webserver.bottle.template(*args, **kwargs)#

Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).

arelle.webserver.bottle.mako_template#

‘partial(…)’

arelle.webserver.bottle.cheetah_template#

‘partial(…)’

arelle.webserver.bottle.jinja2_template#

‘partial(…)’

arelle.webserver.bottle.view(tpl_name, **defaults)#

Decorator: renders a template for a handler. The handler can control its behavior like that:

  • return a dict of template vars to fill out the template

  • return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters.

arelle.webserver.bottle.mako_view#

‘partial(…)’

arelle.webserver.bottle.cheetah_view#

‘partial(…)’

arelle.webserver.bottle.jinja2_view#

‘partial(…)’

arelle.webserver.bottle.TEMPLATE_PATH#

[‘./’, ‘./views/’]

arelle.webserver.bottle.TEMPLATES#

None

arelle.webserver.bottle.DEBUG#

False

arelle.webserver.bottle.NORUN#

False

arelle.webserver.bottle.HTTP_CODES#

‘copy(…)’

arelle.webserver.bottle._HTTP_STATUS_LINES#

‘dict(…)’

arelle.webserver.bottle.ERROR_PAGE_TEMPLATE#

None

arelle.webserver.bottle.request#

‘LocalRequest(…)’

arelle.webserver.bottle.response#

‘LocalResponse(…)’

arelle.webserver.bottle.local#

‘local(…)’

arelle.webserver.bottle.ext#

None

arelle.webserver.bottle._main(argv)#