index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
6,233
bottle
get
Equals :meth:`route`.
def get(self, path=None, method='GET', **options): """ Equals :meth:`route`. """ return self.route(path, method, **options)
(self, path=None, method='GET', **options)
6,234
bottle
get_url
Return a string that matches a named route
def get_url(self, routename, **kargs): """ Return a string that matches a named route """ scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/' location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location)
(self, routename, **kargs)
6,235
bottle
hook
Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.
def hook(self, name): """ Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.""" def decorator(func): self.add_hook(name, func) return func return decorator
(self, name)
6,236
bottle
install
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.
def install(self, 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. ''' if hasattr(plugin, 'setup'): plugin.setup(self) if not callable(plugin) and not hasattr(plugin, 'apply'): raise TypeError("Plugins must be callable or implement .apply()") self.plugins.append(plugin) self.reset() return plugin
(self, plugin)
6,237
bottle
match
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.
def match(self, 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.""" return self.router.match(environ)
(self, environ)
6,238
bottle
merge
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.
def merge(self, 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. ''' if isinstance(routes, Bottle): routes = routes.routes for route in routes: self.add_route(route)
(self, routes)
6,239
bottle
mount
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI application. All other parameters are passed to the underlying :meth:`route` call.
def mount(self, prefix, app, **options): ''' Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :class:`Bottle` or a WSGI application. All other parameters are passed to the underlying :meth:`route` call. ''' if isinstance(app, basestring): depr('Parameter order of Bottle.mount() changed.', True) # 0.10 segments = [p for p in prefix.split('/') if p] if not segments: raise ValueError('Empty path prefix.') path_depth = len(segments) def mountpoint_wrapper(): try: request.path_shift(path_depth) rs = HTTPResponse([]) def start_response(status, headerlist, exc_info=None): if exc_info: try: _raise(*exc_info) finally: exc_info = None rs.status = status for name, value in headerlist: rs.add_header(name, value) return rs.body.append body = app(request.environ, start_response) if body and rs.body: body = itertools.chain(rs.body, body) rs.body = body or rs.body return rs finally: request.path_shift(-path_depth) options.setdefault('skip', True) options.setdefault('method', 'PROXY') options.setdefault('mountpoint', {'prefix': prefix, 'target': app}) options['callback'] = mountpoint_wrapper self.route('/%s/<:re:.*>' % '/'.join(segments), **options) if not prefix.endswith('/'): self.route('/' + '/'.join(segments), **options)
(self, prefix, app, **options)
6,240
bottle
post
Equals :meth:`route` with a ``POST`` method parameter.
def post(self, path=None, method='POST', **options): """ Equals :meth:`route` with a ``POST`` method parameter. """ return self.route(path, method, **options)
(self, path=None, method='POST', **options)
6,241
bottle
put
Equals :meth:`route` with a ``PUT`` method parameter.
def put(self, path=None, method='PUT', **options): """ Equals :meth:`route` with a ``PUT`` method parameter. """ return self.route(path, method, **options)
(self, path=None, method='PUT', **options)
6,242
bottle
remove_hook
Remove a callback from a hook.
def remove_hook(self, name, func): ''' Remove a callback from a hook. ''' if name in self._hooks and func in self._hooks[name]: self._hooks[name].remove(func) return True
(self, name, func)
6,243
bottle
reset
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.
def reset(self, 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. ''' if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] else: routes = [self.routes[route]] for route in routes: route.reset() if DEBUG: for route in routes: route.prepare() self.trigger_hook('app_reset')
(self, route=None)
6,244
bottle
route
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. :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 :meth:`Plugin.apply`).
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ 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. :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 :meth:`Plugin.apply`). """ if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): # TODO: Documentation and tests if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.add_route(route) return callback return decorator(callback) if callback else decorator
(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config)
6,245
bottle
run
Calls :func:`run` with the same parameters.
def run(self, **kwargs): ''' Calls :func:`run` with the same parameters. ''' run(self, **kwargs)
(self, **kwargs)
6,246
bottle
trigger_hook
Trigger a hook and return a list of results.
def trigger_hook(self, __name, *args, **kwargs): ''' Trigger a hook and return a list of results. ''' return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
(self, _Bottle__name, *args, **kwargs)
6,247
bottle
uninstall
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.
def uninstall(self, 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. ''' removed, remove = [], plugin for i, plugin in list(enumerate(self.plugins))[::-1]: if remove is True or remove is plugin or remove is type(plugin) \ or getattr(plugin, 'name', True) == remove: removed.append(plugin) del self.plugins[i] if hasattr(plugin, 'close'): plugin.close() if removed: self.reset() return removed
(self, plugin)
6,248
bottle
wsgi
The bottle WSGI-interface.
def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(_e())), html_escape(format_exc())) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info()) return [tob(err)]
(self, environ, start_response)
6,249
bottle
BottleException
A base class for exceptions used by bottle.
class BottleException(Exception): """ A base class for exceptions used by bottle. """ pass
null
6,250
_io
BytesIO
Buffered I/O implementation using an in-memory bytes buffer.
from _io import BytesIO
(initial_bytes=b'')
6,251
bottle
CGIServer
null
class CGIServer(ServerAdapter): quiet = True def run(self, handler): # pragma: no cover from wsgiref.handlers import CGIHandler def fixed_environ(environ, start_response): environ.setdefault('PATH_INFO', '') return handler(environ, start_response) CGIHandler().run(fixed_environ)
(host='127.0.0.1', port=8080, **options)
6,254
bottle
run
null
def run(self, handler): # pragma: no cover from wsgiref.handlers import CGIHandler def fixed_environ(environ, start_response): environ.setdefault('PATH_INFO', '') return handler(environ, start_response) CGIHandler().run(fixed_environ)
(self, handler)
6,255
bottle
CheetahTemplate
null
class CheetahTemplate(BaseTemplate): def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options) def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) self.context.vars.update(self.defaults) self.context.vars.update(kwargs) out = str(self.tpl) self.context.vars.clear() return out
(source=None, name=None, lookup=[], encoding='utf8', **settings)
6,257
bottle
prepare
null
def prepare(self, **options): from Cheetah.Template import Template self.context = threading.local() self.context.vars = {} options['searchList'] = [self.context.vars] if self.source: self.tpl = Template(source=self.source, **options) else: self.tpl = Template(file=self.filename, **options)
(self, **options)
6,258
bottle
render
null
def render(self, *args, **kwargs): for dictarg in args: kwargs.update(dictarg) self.context.vars.update(self.defaults) self.context.vars.update(kwargs) out = str(self.tpl) self.context.vars.clear() return out
(self, *args, **kwargs)
6,259
bottle
CherootServer
null
class CherootServer(ServerAdapter): def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop()
(host='127.0.0.1', port=8080, **options)
6,262
bottle
run
null
def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop()
(self, handler)
6,263
bottle
CherryPyServer
null
class CherryPyServer(ServerAdapter): def run(self, handler): # pragma: no cover depr("The wsgi server part of cherrypy was split into a new " "project called 'cheroot'. Use the 'cheroot' server " "adapter instead of cherrypy.") from cherrypy import wsgiserver # This will fail for CherryPy >= 9 self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.get('certfile') if certfile: del self.options['certfile'] keyfile = self.options.get('keyfile') if keyfile: del self.options['keyfile'] server = wsgiserver.CherryPyWSGIServer(**self.options) if certfile: server.ssl_certificate = certfile if keyfile: server.ssl_private_key = keyfile try: server.start() finally: server.stop()
(host='127.0.0.1', port=8080, **options)
6,266
bottle
run
null
def run(self, handler): # pragma: no cover depr("The wsgi server part of cherrypy was split into a new " "project called 'cheroot'. Use the 'cheroot' server " "adapter instead of cherrypy.") from cherrypy import wsgiserver # This will fail for CherryPy >= 9 self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.get('certfile') if certfile: del self.options['certfile'] keyfile = self.options.get('keyfile') if keyfile: del self.options['keyfile'] server = wsgiserver.CherryPyWSGIServer(**self.options) if certfile: server.ssl_certificate = certfile if keyfile: server.ssl_private_key = keyfile try: server.start() finally: server.stop()
(self, handler)
6,267
bottle
ConfigDict
A dict-like configuration storage with additional support for namespaces, validators, meta-data, on_change listeners and more. This storage is optimized for fast read access. Retrieving a key or using non-altering dict methods (e.g. `dict.get()`) has no overhead compared to a native dict.
class ConfigDict(dict): ''' A dict-like configuration storage with additional support for namespaces, validators, meta-data, on_change listeners and more. This storage is optimized for fast read access. Retrieving a key or using non-altering dict methods (e.g. `dict.get()`) has no overhead compared to a native dict. ''' __slots__ = ('_meta', '_on_change') class Namespace(DictMixin): def __init__(self, config, namespace): self._config = config self._prefix = namespace def __getitem__(self, key): depr('Accessing namespaces as dicts is discouraged. ' 'Only use flat item access: ' 'cfg["names"]["pace"]["key"] -> cfg["name.space.key"]') #0.12 return self._config[self._prefix + '.' + key] def __setitem__(self, key, value): self._config[self._prefix + '.' + key] = value def __delitem__(self, key): del self._config[self._prefix + '.' + key] def __iter__(self): ns_prefix = self._prefix + '.' for key in self._config: ns, dot, name = key.rpartition('.') if ns == self._prefix and name: yield name def keys(self): return [x for x in self] def __len__(self): return len(self.keys()) def __contains__(self, key): return self._prefix + '.' + key in self._config def __repr__(self): return '<Config.Namespace %s.*>' % self._prefix def __str__(self): return '<Config.Namespace %s.*>' % self._prefix # Deprecated ConfigDict features def __getattr__(self, key): depr('Attribute access is deprecated.') #0.12 if key not in self and key[0].isupper(): self[key] = ConfigDict.Namespace(self._config, self._prefix + '.' + key) if key not in self and key.startswith('__'): raise AttributeError(key) return self.get(key) def __setattr__(self, key, value): if key in ('_config', '_prefix'): self.__dict__[key] = value return depr('Attribute assignment is deprecated.') #0.12 if hasattr(DictMixin, key): raise AttributeError('Read-only attribute.') if key in self and self[key] and isinstance(self[key], self.__class__): raise AttributeError('Non-empty namespace attribute.') self[key] = value def __delattr__(self, key): if key in self: val = self.pop(key) if isinstance(val, self.__class__): prefix = key + '.' for key in self: if key.startswith(prefix): del self[prefix+key] def __call__(self, *a, **ka): depr('Calling ConfDict is deprecated. Use the update() method.') #0.12 self.update(*a, **ka) return self def __init__(self, *a, **ka): self._meta = {} self._on_change = lambda name, value: None if a or ka: depr('Constructor does no longer accept parameters.') #0.12 self.update(*a, **ka) def load_config(self, filename): ''' Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). ''' conf = ConfigParser() conf.read(filename) for section in conf.sections(): for key, value in conf.items(section): if section not in ('DEFAULT', 'bottle'): key = section + '.' + key self[key] = value return self def load_dict(self, source, namespace='', make_namespaces=False): ''' Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'} ''' stack = [(namespace, source)] while stack: prefix, source = stack.pop() if not isinstance(source, dict): raise TypeError('Source is not a dict (r)' % type(key)) for key, value in source.items(): if not isinstance(key, basestring): raise TypeError('Key is not a string (%r)' % type(key)) full_key = prefix + '.' + key if prefix else key if isinstance(value, dict): stack.append((full_key, value)) if make_namespaces: self[full_key] = self.Namespace(self, full_key) else: self[full_key] = value return self def update(self, *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(). Example: ``update('some.namespace', key='value')`` ''' prefix = '' if a and isinstance(a[0], basestring): prefix = a[0].strip('.') + '.' a = a[1:] for key, value in dict(*a, **ka).items(): self[prefix+key] = value def setdefault(self, key, value): if key not in self: self[key] = value return self[key] def __setitem__(self, key, value): if not isinstance(key, basestring): raise TypeError('Key has type %r (not a string)' % type(key)) value = self.meta_get(key, 'filter', lambda x: x)(value) if key in self and self[key] is value: return self._on_change(key, value) dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) def clear(self): for key in self: del self[key] def meta_get(self, key, metafield, default=None): ''' Return the value of a meta field for a key. ''' return self._meta.get(key, {}).get(metafield, default) def meta_set(self, key, metafield, value): ''' Set the meta field for a key to a new value. This triggers the on-change handler for existing keys. ''' self._meta.setdefault(key, {})[metafield] = value if key in self: self[key] = self[key] def meta_list(self, key): ''' Return an iterable of meta field names defined for a key. ''' return self._meta.get(key, {}).keys() # Deprecated ConfigDict features def __getattr__(self, key): depr('Attribute access is deprecated.') #0.12 if key not in self and key[0].isupper(): self[key] = self.Namespace(self, key) if key not in self and key.startswith('__'): raise AttributeError(key) return self.get(key) def __setattr__(self, key, value): if key in self.__slots__: return dict.__setattr__(self, key, value) depr('Attribute assignment is deprecated.') #0.12 if hasattr(dict, key): raise AttributeError('Read-only attribute.') if key in self and self[key] and isinstance(self[key], self.Namespace): raise AttributeError('Non-empty namespace attribute.') self[key] = value def __delattr__(self, key): if key in self: val = self.pop(key) if isinstance(val, self.Namespace): prefix = key + '.' for key in self: if key.startswith(prefix): del self[prefix+key] def __call__(self, *a, **ka): depr('Calling ConfDict is deprecated. Use the update() method.') #0.12 self.update(*a, **ka) return self
(*a, **ka)
6,268
bottle
__call__
null
def __call__(self, *a, **ka): depr('Calling ConfDict is deprecated. Use the update() method.') #0.12 self.update(*a, **ka) return self
(self, *a, **ka)
6,269
bottle
__delattr__
null
def __delattr__(self, key): if key in self: val = self.pop(key) if isinstance(val, self.Namespace): prefix = key + '.' for key in self: if key.startswith(prefix): del self[prefix+key]
(self, key)
6,270
bottle
__delitem__
null
def __delitem__(self, key): dict.__delitem__(self, key)
(self, key)
6,271
bottle
__getattr__
null
def __getattr__(self, key): depr('Attribute access is deprecated.') #0.12 if key not in self and key[0].isupper(): self[key] = self.Namespace(self, key) if key not in self and key.startswith('__'): raise AttributeError(key) return self.get(key)
(self, key)
6,272
bottle
__init__
null
def __init__(self, *a, **ka): self._meta = {} self._on_change = lambda name, value: None if a or ka: depr('Constructor does no longer accept parameters.') #0.12 self.update(*a, **ka)
(self, *a, **ka)
6,273
bottle
__setattr__
null
def __setattr__(self, key, value): if key in self.__slots__: return dict.__setattr__(self, key, value) depr('Attribute assignment is deprecated.') #0.12 if hasattr(dict, key): raise AttributeError('Read-only attribute.') if key in self and self[key] and isinstance(self[key], self.Namespace): raise AttributeError('Non-empty namespace attribute.') self[key] = value
(self, key, value)
6,274
bottle
__setitem__
null
def __setitem__(self, key, value): if not isinstance(key, basestring): raise TypeError('Key has type %r (not a string)' % type(key)) value = self.meta_get(key, 'filter', lambda x: x)(value) if key in self and self[key] is value: return self._on_change(key, value) dict.__setitem__(self, key, value)
(self, key, value)
6,275
bottle
clear
null
def clear(self): for key in self: del self[key]
(self)
6,276
bottle
load_config
Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
def load_config(self, filename): ''' Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). ''' conf = ConfigParser() conf.read(filename) for section in conf.sections(): for key, value in conf.items(section): if section not in ('DEFAULT', 'bottle'): key = section + '.' + key self[key] = value return self
(self, filename)
6,277
bottle
load_dict
Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'}
def load_dict(self, source, namespace='', make_namespaces=False): ''' Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'} ''' stack = [(namespace, source)] while stack: prefix, source = stack.pop() if not isinstance(source, dict): raise TypeError('Source is not a dict (r)' % type(key)) for key, value in source.items(): if not isinstance(key, basestring): raise TypeError('Key is not a string (%r)' % type(key)) full_key = prefix + '.' + key if prefix else key if isinstance(value, dict): stack.append((full_key, value)) if make_namespaces: self[full_key] = self.Namespace(self, full_key) else: self[full_key] = value return self
(self, source, namespace='', make_namespaces=False)
6,278
bottle
meta_get
Return the value of a meta field for a key.
def meta_get(self, key, metafield, default=None): ''' Return the value of a meta field for a key. ''' return self._meta.get(key, {}).get(metafield, default)
(self, key, metafield, default=None)
6,279
bottle
meta_list
Return an iterable of meta field names defined for a key.
def meta_list(self, key): ''' Return an iterable of meta field names defined for a key. ''' return self._meta.get(key, {}).keys()
(self, key)
6,280
bottle
meta_set
Set the meta field for a key to a new value. This triggers the on-change handler for existing keys.
def meta_set(self, key, metafield, value): ''' Set the meta field for a key to a new value. This triggers the on-change handler for existing keys. ''' self._meta.setdefault(key, {})[metafield] = value if key in self: self[key] = self[key]
(self, key, metafield, value)
6,281
bottle
setdefault
null
def setdefault(self, key, value): if key not in self: self[key] = value return self[key]
(self, key, value)
6,282
bottle
update
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(). Example: ``update('some.namespace', key='value')``
def update(self, *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(). Example: ``update('some.namespace', key='value')`` ''' prefix = '' if a and isinstance(a[0], basestring): prefix = a[0].strip('.') + '.' a = a[1:] for key, value in dict(*a, **ka).items(): self[prefix+key] = value
(self, *a, **ka)
6,283
configparser
ConfigParser
ConfigParser implementing interpolation.
class ConfigParser(RawConfigParser): """ConfigParser implementing interpolation.""" _DEFAULT_INTERPOLATION = BasicInterpolation() def set(self, section, option, value=None): """Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.""" self._validate_value_types(option=option, value=value) super().set(section, option, value) def add_section(self, section): """Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.""" self._validate_value_types(section=section) super().add_section(section) def _read_defaults(self, defaults): """Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API. Does not perform interpolation for backwards compatibility. """ try: hold_interpolation = self._interpolation self._interpolation = Interpolation() self.read_dict({self.default_section: defaults}) finally: self._interpolation = hold_interpolation
(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object at 0x7f454e629be0>, converters=<object object at 0x7f454e629be0>)
6,284
configparser
__contains__
null
def __contains__(self, key): return key == self.default_section or self.has_section(key)
(self, key)
6,285
configparser
__delitem__
null
def __delitem__(self, key): if key == self.default_section: raise ValueError("Cannot remove the default section.") if not self.has_section(key): raise KeyError(key) self.remove_section(key)
(self, key)
6,287
configparser
__getitem__
null
def __getitem__(self, key): if key != self.default_section and not self.has_section(key): raise KeyError(key) return self._proxies[key]
(self, key)
6,288
configparser
__init__
null
def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=DEFAULTSECT, interpolation=_UNSET, converters=_UNSET): self._dict = dict_type self._sections = self._dict() self._defaults = self._dict() self._converters = ConverterMapping(self) self._proxies = self._dict() self._proxies[default_section] = SectionProxy(self, default_section) self._delimiters = tuple(delimiters) if delimiters == ('=', ':'): self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE else: d = "|".join(re.escape(d) for d in delimiters) if allow_no_value: self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d), re.VERBOSE) else: self._optcre = re.compile(self._OPT_TMPL.format(delim=d), re.VERBOSE) self._comment_prefixes = tuple(comment_prefixes or ()) self._inline_comment_prefixes = tuple(inline_comment_prefixes or ()) self._strict = strict self._allow_no_value = allow_no_value self._empty_lines_in_values = empty_lines_in_values self.default_section=default_section self._interpolation = interpolation if self._interpolation is _UNSET: self._interpolation = self._DEFAULT_INTERPOLATION if self._interpolation is None: self._interpolation = Interpolation() if converters is not _UNSET: self._converters.update(converters) if defaults: self._read_defaults(defaults)
(self, defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object at 0x7f454e629be0>, converters=<object object at 0x7f454e629be0>)
6,289
configparser
__iter__
null
def __iter__(self): # XXX does it break when underlying container state changed? return itertools.chain((self.default_section,), self._sections.keys())
(self)
6,290
configparser
__len__
null
def __len__(self): return len(self._sections) + 1 # the default section
(self)
6,291
configparser
__setitem__
null
def __setitem__(self, key, value): # To conform with the mapping protocol, overwrites existing values in # the section. if key in self and self[key] is value: return # XXX this is not atomic if read_dict fails at any point. Then again, # no update method in configparser is atomic in this implementation. if key == self.default_section: self._defaults.clear() elif key in self._sections: self._sections[key].clear() self.read_dict({key: value})
(self, key, value)
6,292
configparser
_convert_to_boolean
Return a boolean value translating from other types if necessary.
def _convert_to_boolean(self, value): """Return a boolean value translating from other types if necessary. """ if value.lower() not in self.BOOLEAN_STATES: raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()]
(self, value)
6,293
configparser
_get
null
def _get(self, section, conv, option, **kwargs): return conv(self.get(section, option, **kwargs))
(self, section, conv, option, **kwargs)
6,294
configparser
_get_conv
null
def _get_conv(self, section, option, conv, *, raw=False, vars=None, fallback=_UNSET, **kwargs): try: return self._get(section, conv, option, raw=raw, vars=vars, **kwargs) except (NoSectionError, NoOptionError): if fallback is _UNSET: raise return fallback
(self, section, option, conv, *, raw=False, vars=None, fallback=<object object at 0x7f454e629be0>, **kwargs)
6,295
configparser
_handle_error
null
def _handle_error(self, exc, fpname, lineno, line): if not exc: exc = ParsingError(fpname) exc.append(lineno, repr(line)) return exc
(self, exc, fpname, lineno, line)
6,296
configparser
_join_multiline_values
null
def _join_multiline_values(self): defaults = self.default_section, self._defaults all_sections = itertools.chain((defaults,), self._sections.items()) for section, options in all_sections: for name, val in options.items(): if isinstance(val, list): val = '\n'.join(val).rstrip() options[name] = self._interpolation.before_read(self, section, name, val)
(self)
6,297
configparser
_read
Parse a sectioned configuration file. Each section in a configuration file contains a header, indicated by a name in square brackets (`[]`), plus key/value options, indicated by `name` and `value` delimited with a specific substring (`=` or `:` by default). Values can span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser's mode, blank lines may be treated as parts of multiline values or ignored. Configuration files may include comments, prefixed by specific characters (`#` and `;` by default). Comments may appear on their own in an otherwise empty line or may be entered in lines holding values or section names. Please note that comments get stripped off when reading configuration files.
def _read(self, fp, fpname): """Parse a sectioned configuration file. Each section in a configuration file contains a header, indicated by a name in square brackets (`[]`), plus key/value options, indicated by `name` and `value` delimited with a specific substring (`=` or `:` by default). Values can span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser's mode, blank lines may be treated as parts of multiline values or ignored. Configuration files may include comments, prefixed by specific characters (`#` and `;` by default). Comments may appear on their own in an otherwise empty line or may be entered in lines holding values or section names. Please note that comments get stripped off when reading configuration files. """ elements_added = set() cursect = None # None, or a dictionary sectname = None optname = None lineno = 0 indent_level = 0 e = None # None, or an exception for lineno, line in enumerate(fp, start=1): comment_start = sys.maxsize # strip inline comments inline_prefixes = {p: -1 for p in self._inline_comment_prefixes} while comment_start == sys.maxsize and inline_prefixes: next_prefixes = {} for prefix, index in inline_prefixes.items(): index = line.find(prefix, index+1) if index == -1: continue next_prefixes[prefix] = index if index == 0 or (index > 0 and line[index-1].isspace()): comment_start = min(comment_start, index) inline_prefixes = next_prefixes # strip full line comments for prefix in self._comment_prefixes: if line.strip().startswith(prefix): comment_start = 0 break if comment_start == sys.maxsize: comment_start = None value = line[:comment_start].strip() if not value: if self._empty_lines_in_values: # add empty line to the value, but only if there was no # comment on the line if (comment_start is None and cursect is not None and optname and cursect[optname] is not None): cursect[optname].append('') # newlines added at join else: # empty line marks end of value indent_level = sys.maxsize continue # continuation line? first_nonspace = self.NONSPACECRE.search(line) cur_indent_level = first_nonspace.start() if first_nonspace else 0 if (cursect is not None and optname and cur_indent_level > indent_level): cursect[optname].append(value) # a section header or option header? else: indent_level = cur_indent_level # is it a section header? mo = self.SECTCRE.match(value) if mo: sectname = mo.group('header') if sectname in self._sections: if self._strict and sectname in elements_added: raise DuplicateSectionError(sectname, fpname, lineno) cursect = self._sections[sectname] elements_added.add(sectname) elif sectname == self.default_section: cursect = self._defaults else: cursect = self._dict() self._sections[sectname] = cursect self._proxies[sectname] = SectionProxy(self, sectname) elements_added.add(sectname) # So sections can't start with a continuation line optname = None # no section header in the file? elif cursect is None: raise MissingSectionHeaderError(fpname, lineno, line) # an option line? else: mo = self._optcre.match(value) if mo: optname, vi, optval = mo.group('option', 'vi', 'value') if not optname: e = self._handle_error(e, fpname, lineno, line) optname = self.optionxform(optname.rstrip()) if (self._strict and (sectname, optname) in elements_added): raise DuplicateOptionError(sectname, optname, fpname, lineno) elements_added.add((sectname, optname)) # This check is fine because the OPTCRE cannot # match if it would set optval to None if optval is not None: optval = optval.strip() cursect[optname] = [optval] else: # valueless option handling cursect[optname] = None else: # a non-fatal parsing error occurred. set up the # exception but keep going. the exception will be # raised at the end of the file and will contain a # list of all bogus lines e = self._handle_error(e, fpname, lineno, line) self._join_multiline_values() # if any parsing errors occurred, raise an exception if e: raise e
(self, fp, fpname)
6,298
configparser
_read_defaults
Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API. Does not perform interpolation for backwards compatibility.
def _read_defaults(self, defaults): """Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API. Does not perform interpolation for backwards compatibility. """ try: hold_interpolation = self._interpolation self._interpolation = Interpolation() self.read_dict({self.default_section: defaults}) finally: self._interpolation = hold_interpolation
(self, defaults)
6,299
configparser
_unify_values
Create a sequence of lookups with 'vars' taking priority over the 'section' which takes priority over the DEFAULTSECT.
def _unify_values(self, section, vars): """Create a sequence of lookups with 'vars' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ sectiondict = {} try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) from None # Update with the entry specific variables vardict = {} if vars: for key, value in vars.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value return _ChainMap(vardict, sectiondict, self._defaults)
(self, section, vars)
6,300
configparser
_validate_value_types
Raises a TypeError for non-string values. The only legal non-string value if we allow valueless options is None, so we need to check if the value is a string if: - we do not allow valueless options, or - we allow valueless options but the value is not None For compatibility reasons this method is not used in classic set() for RawConfigParsers. It is invoked in every case for mapping protocol access and in ConfigParser.set().
def _validate_value_types(self, *, section="", option="", value=""): """Raises a TypeError for non-string values. The only legal non-string value if we allow valueless options is None, so we need to check if the value is a string if: - we do not allow valueless options, or - we allow valueless options but the value is not None For compatibility reasons this method is not used in classic set() for RawConfigParsers. It is invoked in every case for mapping protocol access and in ConfigParser.set(). """ if not isinstance(section, str): raise TypeError("section names must be strings") if not isinstance(option, str): raise TypeError("option keys must be strings") if not self._allow_no_value or value: if not isinstance(value, str): raise TypeError("option values must be strings")
(self, *, section='', option='', value='')
6,301
configparser
_write_section
Write a single section to the specified `fp`.
def _write_section(self, fp, section_name, section_items, delimiter): """Write a single section to the specified `fp`.""" fp.write("[{}]\n".format(section_name)) for key, value in section_items: value = self._interpolation.before_write(self, section_name, key, value) if value is not None or not self._allow_no_value: value = delimiter + str(value).replace('\n', '\n\t') else: value = "" fp.write("{}{}\n".format(key, value)) fp.write("\n")
(self, fp, section_name, section_items, delimiter)
6,302
configparser
add_section
Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.
def add_section(self, section): """Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.""" self._validate_value_types(section=section) super().add_section(section)
(self, section)
6,304
configparser
defaults
null
def defaults(self): return self._defaults
(self)
6,305
configparser
get
Get an option value for a given section. If `vars` is provided, it must be a dictionary. The option is looked up in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order. If the key is not found and `fallback` is provided, it is used as a fallback value. `None` can be provided as a `fallback` value. If interpolation is enabled and the optional argument `raw` is False, all interpolations are expanded in the return values. Arguments `raw`, `vars`, and `fallback` are keyword only. The section DEFAULT is special.
def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET): """Get an option value for a given section. If `vars` is provided, it must be a dictionary. The option is looked up in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order. If the key is not found and `fallback` is provided, it is used as a fallback value. `None` can be provided as a `fallback` value. If interpolation is enabled and the optional argument `raw` is False, all interpolations are expanded in the return values. Arguments `raw`, `vars`, and `fallback` are keyword only. The section DEFAULT is special. """ try: d = self._unify_values(section, vars) except NoSectionError: if fallback is _UNSET: raise else: return fallback option = self.optionxform(option) try: value = d[option] except KeyError: if fallback is _UNSET: raise NoOptionError(option, section) else: return fallback if raw or value is None: return value else: return self._interpolation.before_get(self, section, option, value, d)
(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x7f454e629be0>)
6,306
configparser
getboolean
null
def getboolean(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, self._convert_to_boolean, raw=raw, vars=vars, fallback=fallback, **kwargs)
(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x7f454e629be0>, **kwargs)
6,307
configparser
getfloat
null
def getfloat(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, float, raw=raw, vars=vars, fallback=fallback, **kwargs)
(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x7f454e629be0>, **kwargs)
6,308
configparser
getint
null
def getint(self, section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs): return self._get_conv(section, option, int, raw=raw, vars=vars, fallback=fallback, **kwargs)
(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x7f454e629be0>, **kwargs)
6,309
configparser
has_option
Check for the existence of a given option in a given section. If the specified `section` is None or an empty string, DEFAULT is assumed. If the specified `section` does not exist, returns False.
def has_option(self, section, option): """Check for the existence of a given option in a given section. If the specified `section` is None or an empty string, DEFAULT is assumed. If the specified `section` does not exist, returns False.""" if not section or section == self.default_section: option = self.optionxform(option) return option in self._defaults elif section not in self._sections: return False else: option = self.optionxform(option) return (option in self._sections[section] or option in self._defaults)
(self, section, option)
6,310
configparser
has_section
Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged.
def has_section(self, section): """Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged. """ return section in self._sections
(self, section)
6,311
configparser
items
Return a list of (name, value) tuples for each option in a section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw` is true. Additional substitutions may be provided using the `vars` argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special.
def items(self, section=_UNSET, raw=False, vars=None): """Return a list of (name, value) tuples for each option in a section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw` is true. Additional substitutions may be provided using the `vars` argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. """ if section is _UNSET: return super().items() d = self._defaults.copy() try: d.update(self._sections[section]) except KeyError: if section != self.default_section: raise NoSectionError(section) orig_keys = list(d.keys()) # Update with the entry specific variables if vars: for key, value in vars.items(): d[self.optionxform(key)] = value value_getter = lambda option: self._interpolation.before_get(self, section, option, d[option], d) if raw: value_getter = lambda option: d[option] return [(option, value_getter(option)) for option in orig_keys]
(self, section=<object object at 0x7f454e629be0>, raw=False, vars=None)
6,313
configparser
options
Return a list of option names for the given section name.
def options(self, section): """Return a list of option names for the given section name.""" try: opts = self._sections[section].copy() except KeyError: raise NoSectionError(section) from None opts.update(self._defaults) return list(opts.keys())
(self, section)
6,314
configparser
optionxform
null
def optionxform(self, optionstr): return optionstr.lower()
(self, optionstr)
6,316
configparser
popitem
Remove a section from the parser and return it as a (section_name, section_proxy) tuple. If no section is present, raise KeyError. The section DEFAULT is never returned because it cannot be removed.
def popitem(self): """Remove a section from the parser and return it as a (section_name, section_proxy) tuple. If no section is present, raise KeyError. The section DEFAULT is never returned because it cannot be removed. """ for key in self.sections(): value = self[key] del self[key] return key, value raise KeyError
(self)
6,317
configparser
read
Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given. Return list of successfully read files.
def read(self, filenames, encoding=None): """Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given. Return list of successfully read files. """ if isinstance(filenames, (str, bytes, os.PathLike)): filenames = [filenames] encoding = io.text_encoding(encoding) read_ok = [] for filename in filenames: try: with open(filename, encoding=encoding) as fp: self._read(fp, filename) except OSError: continue if isinstance(filename, os.PathLike): filename = os.fspath(filename) read_ok.append(filename) return read_ok
(self, filenames, encoding=None)
6,318
configparser
read_dict
Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. All types held in the dictionary are converted to strings during reading, including section names, option names and keys. Optional second argument is the `source` specifying the name of the dictionary being read.
def read_dict(self, dictionary, source='<dict>'): """Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. All types held in the dictionary are converted to strings during reading, including section names, option names and keys. Optional second argument is the `source` specifying the name of the dictionary being read. """ elements_added = set() for section, keys in dictionary.items(): section = str(section) try: self.add_section(section) except (DuplicateSectionError, ValueError): if self._strict and section in elements_added: raise elements_added.add(section) for key, value in keys.items(): key = self.optionxform(str(key)) if value is not None: value = str(value) if self._strict and (section, key) in elements_added: raise DuplicateOptionError(section, key, source) elements_added.add((section, key)) self.set(section, key, value)
(self, dictionary, source='<dict>')
6,319
configparser
read_file
Like read() but the argument must be a file-like object. The `f` argument must be iterable, returning one line at a time. Optional second argument is the `source` specifying the name of the file being read. If not given, it is taken from f.name. If `f` has no `name` attribute, `<???>` is used.
def read_file(self, f, source=None): """Like read() but the argument must be a file-like object. The `f` argument must be iterable, returning one line at a time. Optional second argument is the `source` specifying the name of the file being read. If not given, it is taken from f.name. If `f` has no `name` attribute, `<???>` is used. """ if source is None: try: source = f.name except AttributeError: source = '<???>' self._read(f, source)
(self, f, source=None)
6,320
configparser
read_string
Read configuration from a given string.
def read_string(self, string, source='<string>'): """Read configuration from a given string.""" sfile = io.StringIO(string) self.read_file(sfile, source)
(self, string, source='<string>')
6,321
configparser
readfp
Deprecated, use read_file instead.
def readfp(self, fp, filename=None): """Deprecated, use read_file instead.""" warnings.warn( "This method will be removed in Python 3.12. " "Use 'parser.read_file()' instead.", DeprecationWarning, stacklevel=2 ) self.read_file(fp, source=filename)
(self, fp, filename=None)
6,322
configparser
remove_option
Remove an option.
def remove_option(self, section, option): """Remove an option.""" if not section or section == self.default_section: sectdict = self._defaults else: try: sectdict = self._sections[section] except KeyError: raise NoSectionError(section) from None option = self.optionxform(option) existed = option in sectdict if existed: del sectdict[option] return existed
(self, section, option)
6,323
configparser
remove_section
Remove a file section.
def remove_section(self, section): """Remove a file section.""" existed = section in self._sections if existed: del self._sections[section] del self._proxies[section] return existed
(self, section)
6,324
configparser
sections
Return a list of section names, excluding [DEFAULT]
def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it return list(self._sections.keys())
(self)
6,325
configparser
set
Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.
def set(self, section, option, value=None): """Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.""" self._validate_value_types(option=option, value=value) super().set(section, option, value)
(self, section, option, value=None)
6,329
configparser
write
Write an .ini-format representation of the configuration state. If `space_around_delimiters` is True (the default), delimiters between keys and values are surrounded by spaces. Please note that comments in the original configuration file are not preserved when writing the configuration back.
def write(self, fp, space_around_delimiters=True): """Write an .ini-format representation of the configuration state. If `space_around_delimiters` is True (the default), delimiters between keys and values are surrounded by spaces. Please note that comments in the original configuration file are not preserved when writing the configuration back. """ if space_around_delimiters: d = " {} ".format(self._delimiters[0]) else: d = self._delimiters[0] if self._defaults: self._write_section(fp, self.default_section, self._defaults.items(), d) for section in self._sections: self._write_section(fp, section, self._sections[section].items(), d)
(self, fp, space_around_delimiters=True)
6,330
collections.abc
MutableMapping
A MutableMapping is a generic container for associating key/value pairs. This class provides concrete generic implementations of all methods except for __getitem__, __setitem__, __delitem__, __iter__, and __len__.
from collections.abc import MutableMapping
()
6,347
bottle
DictProperty
Property that maps to a key in a local dict-like attribute.
class DictProperty(object): ''' Property that maps to a key in a local dict-like attribute. ''' def __init__(self, attr, key=None, read_only=False): self.attr, self.key, self.read_only = attr, key, read_only def __call__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter, self.key = func, self.key or func.__name__ return self def __get__(self, obj, cls): if obj is None: return self key, storage = self.key, getattr(obj, self.attr) if key not in storage: storage[key] = self.getter(obj) return storage[key] def __set__(self, obj, value): if self.read_only: raise AttributeError("Read-Only property.") getattr(obj, self.attr)[self.key] = value def __delete__(self, obj): if self.read_only: raise AttributeError("Read-Only property.") del getattr(obj, self.attr)[self.key]
(attr, key=None, read_only=False)
6,348
bottle
__call__
null
def __call__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter, self.key = func, self.key or func.__name__ return self
(self, func)
6,349
bottle
__delete__
null
def __delete__(self, obj): if self.read_only: raise AttributeError("Read-Only property.") del getattr(obj, self.attr)[self.key]
(self, obj)
6,350
bottle
__get__
null
def __get__(self, obj, cls): if obj is None: return self key, storage = self.key, getattr(obj, self.attr) if key not in storage: storage[key] = self.getter(obj) return storage[key]
(self, obj, cls)
6,351
bottle
__init__
null
def __init__(self, attr, key=None, read_only=False): self.attr, self.key, self.read_only = attr, key, read_only
(self, attr, key=None, read_only=False)
6,352
bottle
__set__
null
def __set__(self, obj, value): if self.read_only: raise AttributeError("Read-Only property.") getattr(obj, self.attr)[self.key] = value
(self, obj, value)
6,353
bottle
DieselServer
Untested.
class DieselServer(ServerAdapter): """ Untested. """ def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run()
(host='127.0.0.1', port=8080, **options)
6,356
bottle
run
null
def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run()
(self, handler)
6,357
bottle
EventletServer
Untested
class EventletServer(ServerAdapter): """ Untested """ def run(self, handler): from eventlet import wsgi, listen try: wsgi.server(listen((self.host, self.port)), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen((self.host, self.port)), handler)
(host='127.0.0.1', port=8080, **options)
6,360
bottle
run
null
def run(self, handler): from eventlet import wsgi, listen try: wsgi.server(listen((self.host, self.port)), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen((self.host, self.port)), handler)
(self, handler)
6,361
bottle
FapwsServer
Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3
class FapwsServer(ServerAdapter): """ Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3 """ def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base, config port = self.port if float(config.SERVER_IDENT[-2:]) > 0.4: # fapws3 silently changed its API in 0.5 port = str(port) evwsgi.start(self.host, port) # fapws3 never releases the GIL. Complain upstream. I tried. No luck. if 'BOTTLE_CHILD' in os.environ and not self.quiet: _stderr("WARNING: Auto-reloading does not work with Fapws3.\n") _stderr(" (Fapws3 breaks python thread support)\n") evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('', app)) evwsgi.run()
(host='127.0.0.1', port=8080, **options)
6,364
bottle
run
null
def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base, config port = self.port if float(config.SERVER_IDENT[-2:]) > 0.4: # fapws3 silently changed its API in 0.5 port = str(port) evwsgi.start(self.host, port) # fapws3 never releases the GIL. Complain upstream. I tried. No luck. if 'BOTTLE_CHILD' in os.environ and not self.quiet: _stderr("WARNING: Auto-reloading does not work with Fapws3.\n") _stderr(" (Fapws3 breaks python thread support)\n") evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('', app)) evwsgi.run()
(self, handler)
6,365
bottle
FileCheckerThread
Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old.
class FileCheckerThread(threading.Thread): ''' Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets to old. ''' def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.lockfile, self.interval = lockfile, interval #: Is one of 'reload', 'error' or 'exit' self.status = None def run(self): exists = os.path.exists mtime = lambda path: os.stat(path).st_mtime files = dict() for module in list(sys.modules.values()): path = getattr(module, '__file__', '') or '' if path[-4:] in ('.pyo', '.pyc'): path = path[:-1] if path and exists(path): files[path] = mtime(path) while not self.status: if not exists(self.lockfile)\ or mtime(self.lockfile) < time.time() - self.interval - 5: self.status = 'error' thread.interrupt_main() for path, lmtime in list(files.items()): if not exists(path) or mtime(path) > lmtime: self.status = 'reload' thread.interrupt_main() break time.sleep(self.interval) def __enter__(self): self.start() def __exit__(self, exc_type, exc_val, exc_tb): if not self.status: self.status = 'exit' # silent exit self.join() return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
(lockfile, interval)
6,366
bottle
__enter__
null
def __enter__(self): self.start()
(self)
6,367
bottle
__exit__
null
def __exit__(self, exc_type, exc_val, exc_tb): if not self.status: self.status = 'exit' # silent exit self.join() return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
(self, exc_type, exc_val, exc_tb)
6,368
bottle
__init__
null
def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.lockfile, self.interval = lockfile, interval #: Is one of 'reload', 'error' or 'exit' self.status = None
(self, lockfile, interval)