signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def all_plugins(self):
unique = set()<EOL>for p in reversed(self.app.plugins + self.plugins):<EOL><INDENT>if True in self.skiplist: break<EOL>name = getattr(p, '<STR_LIT:name>', False)<EOL>if name and (name in self.skiplist or name in unique): continue<EOL>if p in self.skiplist or type(p) in self.skiplist: continue<EOL>if name: unique.add(name)<EOL>yield p<EOL><DEDENT>
Yield all Plugins affecting this route.
f8968:c10:m4
def get_undecorated_callback(self):
func = self.callback<EOL>func = getattr(func, '<STR_LIT>' if py3k else '<STR_LIT>', func)<EOL>closure_attr = '<STR_LIT>' if py3k else '<STR_LIT>'<EOL>while hasattr(func, closure_attr) and getattr(func, closure_attr):<EOL><INDENT>attributes = getattr(func, closure_attr)<EOL>func = attributes[<NUM_LIT:0>].cell_contents<EOL>if not isinstance(func, FunctionType):<EOL><INDENT>func = filter(lambda x: isinstance(x, FunctionType),<EOL>map(lambda x: x.cell_contents, attributes))<EOL>func = list(func)[<NUM_LIT:0>] <EOL><DEDENT><DEDENT>return func<EOL>
Return the callback. If the callback is a decorated function, try to recover the original function.
f8968:c10:m6
def get_callback_args(self):
return getargspec(self.get_undecorated_callback())[<NUM_LIT:0>]<EOL>
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.
f8968:c10:m7
def get_config(self, key, default=None):
depr(<NUM_LIT:0>, <NUM_LIT>, "<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return self.config.get(key, default)<EOL>
Lookup a config field and return its value, first checking the route.config, then route.app.config.
f8968:c10:m8
def add_hook(self, name, func):
if name in self.__hook_reversed:<EOL><INDENT>self._hooks[name].insert(<NUM_LIT:0>, func)<EOL><DEDENT>else:<EOL><INDENT>self._hooks[name].append(func)<EOL><DEDENT>
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.
f8968:c11:m3
def remove_hook(self, name, func):
if name in self._hooks and func in self._hooks[name]:<EOL><INDENT>self._hooks[name].remove(func)<EOL>return True<EOL><DEDENT>
Remove a callback from a hook.
f8968:c11:m4
def trigger_hook(self, __name, *args, **kwargs):
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]<EOL>
Trigger a hook and return a list of results.
f8968:c11:m5
def hook(self, name):
def decorator(func):<EOL><INDENT>self.add_hook(name, func)<EOL>return func<EOL><DEDENT>return decorator<EOL>
Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.
f8968:c11:m6
def mount(self, prefix, app, **options):
if not prefix.startswith('<STR_LIT:/>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if isinstance(app, Bottle):<EOL><INDENT>return self._mount_app(prefix, app, **options)<EOL><DEDENT>else:<EOL><INDENT>return self._mount_wsgi(prefix, app, **options)<EOL><DEDENT>
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: parent_app.mount('/prefix/', child_app) :param prefix: path prefix or `mount-point`. :param 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.
f8968:c11:m9
def merge(self, routes):
if isinstance(routes, Bottle):<EOL><INDENT>routes = routes.routes<EOL><DEDENT>for route in routes:<EOL><INDENT>self.add_route(route)<EOL><DEDENT>
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.
f8968:c11:m10
def install(self, plugin):
if hasattr(plugin, '<STR_LIT>'): plugin.setup(self)<EOL>if not callable(plugin) and not hasattr(plugin, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.plugins.append(plugin)<EOL>self.reset()<EOL>return plugin<EOL>
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.
f8968:c11:m11
def uninstall(self, plugin):
removed, remove = [], plugin<EOL>for i, plugin in list(enumerate(self.plugins))[::-<NUM_LIT:1>]:<EOL><INDENT>if remove is True or remove is plugin or remove is type(plugin)or getattr(plugin, '<STR_LIT:name>', True) == remove:<EOL><INDENT>removed.append(plugin)<EOL>del self.plugins[i]<EOL>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT><DEDENT>if removed: self.reset()<EOL>return removed<EOL>
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.
f8968:c11:m12
def reset(self, route=None):
if route is None: routes = self.routes<EOL>elif isinstance(route, Route): routes = [route]<EOL>else: routes = [self.routes[route]]<EOL>for route in routes:<EOL><INDENT>route.reset()<EOL><DEDENT>if DEBUG:<EOL><INDENT>for route in routes:<EOL><INDENT>route.prepare()<EOL><DEDENT><DEDENT>self.trigger_hook('<STR_LIT>')<EOL>
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.
f8968:c11:m13
def close(self):
for plugin in self.plugins:<EOL><INDENT>if hasattr(plugin, '<STR_LIT>'): plugin.close()<EOL><DEDENT>
Close the application and all installed plugins.
f8968:c11:m14
def run(self, **kwargs):
run(self, **kwargs)<EOL>
Calls :func:`run` with the same parameters.
f8968:c11:m15
def match(self, environ):
return self.router.match(environ)<EOL>
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.
f8968:c11:m16
def get_url(self, routename, **kargs):
scriptname = request.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>location = self.router.build(routename, **kargs).lstrip('<STR_LIT:/>')<EOL>return urljoin(urljoin('<STR_LIT:/>', scriptname), location)<EOL>
Return a string that matches a named route
f8968:c11:m17
def add_route(self, route):
self.routes.append(route)<EOL>self.router.add(route.rule, route.method, route, name=route.name)<EOL>if DEBUG: route.prepare()<EOL>
Add a route object, but do not change the :data:`Route.app` attribute.
f8968:c11:m18
def route(self,<EOL>path=None,<EOL>method='<STR_LIT:GET>',<EOL>callback=None,<EOL>name=None,<EOL>apply=None,<EOL>skip=None, **config):
if callable(path): path, callback = None, path<EOL>plugins = makelist(apply)<EOL>skiplist = makelist(skip)<EOL>def decorator(callback):<EOL><INDENT>if isinstance(callback, basestring): callback = load(callback)<EOL>for rule in makelist(path) or yieldroutes(callback):<EOL><INDENT>for verb in makelist(method):<EOL><INDENT>verb = verb.upper()<EOL>route = Route(self, rule, verb, callback,<EOL>name=name,<EOL>plugins=plugins,<EOL>skiplist=skiplist, **config)<EOL>self.add_route(route)<EOL><DEDENT><DEDENT>return callback<EOL><DEDENT>return decorator(callback) if callback else decorator<EOL>
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`).
f8968:c11:m19
def get(self, path=None, method='<STR_LIT:GET>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route`.
f8968:c11:m20
def post(self, path=None, method='<STR_LIT:POST>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``POST`` method parameter.
f8968:c11:m21
def put(self, path=None, method='<STR_LIT>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``PUT`` method parameter.
f8968:c11:m22
def delete(self, path=None, method='<STR_LIT>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``DELETE`` method parameter.
f8968:c11:m23
def patch(self, path=None, method='<STR_LIT>', **options):
return self.route(path, method, **options)<EOL>
Equals :meth:`route` with a ``PATCH`` method parameter.
f8968:c11:m24
def error(self, code=<NUM_LIT>, callback=None):
def decorator(callback):<EOL><INDENT>if isinstance(callback, basestring): callback = load(callback)<EOL>self.error_handler[int(code)] = callback<EOL>return callback<EOL><DEDENT>return decorator(callback) if callback else decorator<EOL>
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'
f8968:c11:m25
def _cast(self, out, peek=None):
<EOL>if not out:<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return []<EOL><DEDENT>if isinstance(out, (tuple, list))and isinstance(out[<NUM_LIT:0>], (bytes, unicode)):<EOL><INDENT>out = out[<NUM_LIT:0>][<NUM_LIT:0>:<NUM_LIT:0>].join(out) <EOL><DEDENT>if isinstance(out, unicode):<EOL><INDENT>out = out.encode(response.charset)<EOL><DEDENT>if isinstance(out, bytes):<EOL><INDENT>if '<STR_LIT>' not in response:<EOL><INDENT>response['<STR_LIT>'] = len(out)<EOL><DEDENT>return [out]<EOL><DEDENT>if isinstance(out, HTTPError):<EOL><INDENT>out.apply(response)<EOL>out = self.error_handler.get(out.status_code,<EOL>self.default_error_handler)(out)<EOL>return self._cast(out)<EOL><DEDENT>if isinstance(out, HTTPResponse):<EOL><INDENT>out.apply(response)<EOL>return self._cast(out.body)<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' in request.environ:<EOL><INDENT>return request.environ['<STR_LIT>'](out)<EOL><DEDENT>elif hasattr(out, '<STR_LIT>') or not hasattr(out, '<STR_LIT>'):<EOL><INDENT>return WSGIFileWrapper(out)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>iout = iter(out)<EOL>first = next(iout)<EOL>while not first:<EOL><INDENT>first = next(iout)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>return self._cast('<STR_LIT>')<EOL><DEDENT>except HTTPResponse as E:<EOL><INDENT>first = E<EOL><DEDENT>except (KeyboardInterrupt, SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except Exception as error:<EOL><INDENT>if not self.catchall: raise<EOL>first = HTTPError(<NUM_LIT>, '<STR_LIT>', error, format_exc())<EOL><DEDENT>if isinstance(first, HTTPResponse):<EOL><INDENT>return self._cast(first)<EOL><DEDENT>elif isinstance(first, bytes):<EOL><INDENT>new_iter = itertools.chain([first], iout)<EOL><DEDENT>elif isinstance(first, unicode):<EOL><INDENT>encoder = lambda x: x.encode(response.charset)<EOL>new_iter = imap(encoder, itertools.chain([first], iout))<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % type(first)<EOL>return self._cast(HTTPError(<NUM_LIT>, msg))<EOL><DEDENT>if hasattr(out, '<STR_LIT>'):<EOL><INDENT>new_iter = _closeiter(new_iter, out.close)<EOL><DEDENT>return new_iter<EOL>
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
f8968:c11:m28
def wsgi(self, environ, start_response):
try:<EOL><INDENT>out = self._cast(self._handle(environ))<EOL>if response._status_code in (<NUM_LIT:100>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)or environ['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>if hasattr(out, '<STR_LIT>'): out.close()<EOL>out = []<EOL><DEDENT>start_response(response._status_line, response.headerlist)<EOL>return out<EOL><DEDENT>except (KeyboardInterrupt, SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except Exception as E:<EOL><INDENT>if not self.catchall: raise<EOL>err = '<STR_LIT>'% html_escape(environ.get('<STR_LIT>', '<STR_LIT:/>'))<EOL>if DEBUG:<EOL><INDENT>err += '<STR_LIT>''<STR_LIT>'% (html_escape(repr(E)), html_escape(format_exc()))<EOL><DEDENT>environ['<STR_LIT>'].write(err)<EOL>environ['<STR_LIT>'].flush()<EOL>headers = [('<STR_LIT:Content-Type>', '<STR_LIT>')]<EOL>start_response('<STR_LIT>', headers, sys.exc_info())<EOL>return [tob(err)]<EOL><DEDENT>
The bottle WSGI-interface.
f8968:c11:m29
def __call__(self, environ, start_response):
return self.wsgi(environ, start_response)<EOL>
Each instance of :class:'Bottle' is a WSGI application.
f8968:c11:m30
def __enter__(self):
default_app.push(self)<EOL>return self<EOL>
Use this application as default for all module-level shortcuts.
f8968:c11:m31
def __init__(self, environ=None):
<EOL>self.environ = {} if environ is None else environ<EOL>self.environ['<STR_LIT>'] = self<EOL>
Wrap a WSGI environ dictionary.
f8968:c12:m0
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def app(self):<DEDENT>
raise RuntimeError('<STR_LIT>')<EOL>
Bottle application handling this request.
f8968:c12:m1
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def route(self):<DEDENT>
raise RuntimeError('<STR_LIT>')<EOL>
The bottle :class:`Route` object that matches this request.
f8968:c12:m2
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def url_args(self):<DEDENT>
raise RuntimeError('<STR_LIT>')<EOL>
The arguments extracted from the URL.
f8968:c12:m3
@property<EOL><INDENT>def path(self):<DEDENT>
return '<STR_LIT:/>' + self.environ.get('<STR_LIT>', '<STR_LIT>').lstrip('<STR_LIT:/>')<EOL>
The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case).
f8968:c12:m4
@property<EOL><INDENT>def method(self):<DEDENT>
return self.environ.get('<STR_LIT>', '<STR_LIT:GET>').upper()<EOL>
The ``REQUEST_METHOD`` value as an uppercase string.
f8968:c12:m5
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def headers(self):<DEDENT>
return WSGIHeaderDict(self.environ)<EOL>
A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers.
f8968:c12:m6
def get_header(self, name, default=None):
return self.headers.get(name, default)<EOL>
Return the value of a request header, or a given default value.
f8968:c12:m7
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def cookies(self):<DEDENT>
cookies = SimpleCookie(self.environ.get('<STR_LIT>', '<STR_LIT>')).values()<EOL>return FormsDict((c.key, c.value) for c in cookies)<EOL>
Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies.
f8968:c12:m8
def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256):
value = self.cookies.get(key)<EOL>if secret:<EOL><INDENT>if value and value.startswith('<STR_LIT:!>') and '<STR_LIT:?>' in value:<EOL><INDENT>sig, msg = map(tob, value[<NUM_LIT:1>:].split('<STR_LIT:?>', <NUM_LIT:1>))<EOL>hash = hmac.new(tob(secret), msg, digestmod=digestmod).digest()<EOL>if _lscmp(sig, base64.b64encode(hash)):<EOL><INDENT>dst = pickle.loads(base64.b64decode(msg))<EOL>if dst and dst[<NUM_LIT:0>] == key:<EOL><INDENT>return dst[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>return default<EOL><DEDENT>return value or default<EOL>
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.
f8968:c12:m9
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def query(self):<DEDENT>
get = self.environ['<STR_LIT>'] = FormsDict()<EOL>pairs = _parse_qsl(self.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>for key, value in pairs:<EOL><INDENT>get[key] = value<EOL><DEDENT>return get<EOL>
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`.
f8968:c12:m10
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def forms(self):<DEDENT>
forms = FormsDict()<EOL>for name, item in self.POST.allitems():<EOL><INDENT>if not isinstance(item, FileUpload):<EOL><INDENT>forms[name] = item<EOL><DEDENT><DEDENT>return forms<EOL>
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`.
f8968:c12:m11
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def params(self):<DEDENT>
params = FormsDict()<EOL>for key, value in self.query.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>for key, value in self.forms.allitems():<EOL><INDENT>params[key] = value<EOL><DEDENT>return params<EOL>
A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.
f8968:c12:m12
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def files(self):<DEDENT>
files = FormsDict()<EOL>for name, item in self.POST.allitems():<EOL><INDENT>if isinstance(item, FileUpload):<EOL><INDENT>files[name] = item<EOL><DEDENT><DEDENT>return files<EOL>
File uploads parsed from `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`FileUpload`.
f8968:c12:m13
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def json(self):<DEDENT>
ctype = self.environ.get('<STR_LIT>', '<STR_LIT>').lower().split('<STR_LIT:;>')[<NUM_LIT:0>]<EOL>if ctype in ('<STR_LIT:application/json>', '<STR_LIT>'):<EOL><INDENT>b = self._get_body_string()<EOL>if not b:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>return json_loads(b)<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT><DEDENT>return None<EOL>
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.
f8968:c12:m14
def _get_body_string(self):
clen = self.content_length<EOL>if clen > self.MEMFILE_MAX:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>if clen < <NUM_LIT:0>: clen = self.MEMFILE_MAX + <NUM_LIT:1><EOL>data = self.body.read(clen)<EOL>if len(data) > self.MEMFILE_MAX: <EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT>return data<EOL>
read body until content-length or MEMFILE_MAX into a string. Raise HTTPError(413) on requests that are to large.
f8968:c12:m18
@property<EOL><INDENT>def body(self):<DEDENT>
self._body.seek(<NUM_LIT:0>)<EOL>return self._body<EOL>
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.
f8968:c12:m19
@property<EOL><INDENT>def chunked(self):<DEDENT>
return '<STR_LIT>' in self.environ.get(<EOL>'<STR_LIT>', '<STR_LIT>').lower()<EOL>
True if Chunked transfer encoding was.
f8968:c12:m20
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def POST(self):<DEDENT>
post = FormsDict()<EOL>if not self.content_type.startswith('<STR_LIT>'):<EOL><INDENT>pairs = _parse_qsl(tonat(self._get_body_string(), '<STR_LIT>'))<EOL>for key, value in pairs:<EOL><INDENT>post[key] = value<EOL><DEDENT>return post<EOL><DEDENT>safe_env = {'<STR_LIT>': '<STR_LIT>'} <EOL>for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key in self.environ: safe_env[key] = self.environ[key]<EOL><DEDENT>args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)<EOL>if py3k:<EOL><INDENT>args['<STR_LIT>'] = '<STR_LIT:utf8>'<EOL><DEDENT>data = cgi.FieldStorage(**args)<EOL>self['<STR_LIT>'] = data <EOL>data = data.list or []<EOL>for item in data:<EOL><INDENT>if item.filename:<EOL><INDENT>post[item.name] = FileUpload(item.file, item.name,<EOL>item.filename, item.headers)<EOL><DEDENT>else:<EOL><INDENT>post[item.name] = item.value<EOL><DEDENT><DEDENT>return post<EOL>
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).
f8968:c12:m21
@property<EOL><INDENT>def url(self):<DEDENT>
return self.urlparts.geturl()<EOL>
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.
f8968:c12:m22
@DictProperty('<STR_LIT>', '<STR_LIT>', read_only=True)<EOL><INDENT>def urlparts(self):<DEDENT>
env = self.environ<EOL>http = env.get('<STR_LIT>')or env.get('<STR_LIT>', '<STR_LIT:http>')<EOL>host = env.get('<STR_LIT>') or env.get('<STR_LIT>')<EOL>if not host:<EOL><INDENT>host = env.get('<STR_LIT>', '<STR_LIT:127.0.0.1>')<EOL>port = env.get('<STR_LIT>')<EOL>if port and port != ('<STR_LIT>' if http == '<STR_LIT:http>' else '<STR_LIT>'):<EOL><INDENT>host += '<STR_LIT::>' + port<EOL><DEDENT><DEDENT>path = urlquote(self.fullpath)<EOL>return UrlSplitResult(http, host, path, env.get('<STR_LIT>'), '<STR_LIT>')<EOL>
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.
f8968:c12:m23
@property<EOL><INDENT>def fullpath(self):<DEDENT>
return urljoin(self.script_name, self.path.lstrip('<STR_LIT:/>'))<EOL>
Request path including :attr:`script_name` (if present).
f8968:c12:m24
@property<EOL><INDENT>def query_string(self):<DEDENT>
return self.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>
The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string.
f8968:c12:m25
@property<EOL><INDENT>def script_name(self):<DEDENT>
script_name = self.environ.get('<STR_LIT>', '<STR_LIT>').strip('<STR_LIT:/>')<EOL>return '<STR_LIT:/>' + script_name + '<STR_LIT:/>' if script_name else '<STR_LIT:/>'<EOL>
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.
f8968:c12:m26
def path_shift(self, shift=<NUM_LIT:1>):
script, path = path_shift(self.environ.get('<STR_LIT>', '<STR_LIT:/>'), self.path, shift)<EOL>self['<STR_LIT>'], self['<STR_LIT>'] = script, path<EOL>
Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1)
f8968:c12:m27
@property<EOL><INDENT>def content_length(self):<DEDENT>
return int(self.environ.get('<STR_LIT>') or -<NUM_LIT:1>)<EOL>
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.
f8968:c12:m28
@property<EOL><INDENT>def content_type(self):<DEDENT>
return self.environ.get('<STR_LIT>', '<STR_LIT>').lower()<EOL>
The Content-Type header as a lowercase-string (default: empty).
f8968:c12:m29
@property<EOL><INDENT>def is_xhr(self):<DEDENT>
requested_with = self.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>return requested_with.lower() == '<STR_LIT>'<EOL>
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).
f8968:c12:m30
@property<EOL><INDENT>def is_ajax(self):<DEDENT>
return self.is_xhr<EOL>
Alias for :attr:`is_xhr`. "Ajax" is not the right term.
f8968:c12:m31
@property<EOL><INDENT>def auth(self):<DEDENT>
basic = parse_auth(self.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>if basic: return basic<EOL>ruser = self.environ.get('<STR_LIT>')<EOL>if ruser: return (ruser, None)<EOL>return None<EOL>
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.
f8968:c12:m32
@property<EOL><INDENT>def remote_route(self):<DEDENT>
proxy = self.environ.get('<STR_LIT>')<EOL>if proxy: return [ip.strip() for ip in proxy.split('<STR_LIT:U+002C>')]<EOL>remote = self.environ.get('<STR_LIT>')<EOL>return [remote] if remote else []<EOL>
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.
f8968:c12:m33
@property<EOL><INDENT>def remote_addr(self):<DEDENT>
route = self.remote_route<EOL>return route[<NUM_LIT:0>] if route else None<EOL>
The client IP as a string. Note that this information can be forged by malicious clients.
f8968:c12:m34
def copy(self):
return Request(self.environ.copy())<EOL>
Return a new :class:`Request` with a shallow :attr:`environ` copy.
f8968:c12:m35
def __setitem__(self, key, value):
if self.environ.get('<STR_LIT>'):<EOL><INDENT>raise KeyError('<STR_LIT>')<EOL><DEDENT>self.environ[key] = value<EOL>todelete = ()<EOL>if key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT:body>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key == '<STR_LIT>':<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif key.startswith('<STR_LIT>'):<EOL><INDENT>todelete = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>for key in todelete:<EOL><INDENT>self.environ.pop('<STR_LIT>' + key, None)<EOL><DEDENT>
Change an environ value and clear all caches that depend on it.
f8968:c12:m42
def __getattr__(self, name):
try:<EOL><INDENT>var = self.environ['<STR_LIT>' % name]<EOL>return var.__get__(self) if hasattr(var, '<STR_LIT>') else var<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError('<STR_LIT>' % name)<EOL><DEDENT>
Search in self.environ for additional user defined attributes.
f8968:c12:m44
def copy(self, cls=None):
cls = cls or BaseResponse<EOL>assert issubclass(cls, BaseResponse)<EOL>copy = cls()<EOL>copy.status = self.status<EOL>copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())<EOL>if self._cookies:<EOL><INDENT>copy._cookies = SimpleCookie()<EOL>copy._cookies.load(self._cookies.output(header='<STR_LIT>'))<EOL><DEDENT>return copy<EOL>
Returns a copy of self.
f8968:c14:m1
@property<EOL><INDENT>def status_line(self):<DEDENT>
return self._status_line<EOL>
The HTTP status line as a string (e.g. ``404 Not Found``).
f8968:c14:m4
@property<EOL><INDENT>def status_code(self):<DEDENT>
return self._status_code<EOL>
The HTTP status code as an integer (e.g. 404).
f8968:c14:m5
@property<EOL><INDENT>def headers(self):<DEDENT>
hdict = HeaderDict()<EOL>hdict.dict = self._headers<EOL>return hdict<EOL>
An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.
f8968:c14:m8
def get_header(self, name, default=None):
return self._headers.get(_hkey(name), [default])[-<NUM_LIT:1>]<EOL>
Return the value of a previously defined header. If there is no header with that name, return a default value.
f8968:c14:m13
def set_header(self, name, value):
self._headers[_hkey(name)] = [_hval(value)]<EOL>
Create a new response header, replacing any previously defined headers with the same name.
f8968:c14:m14
def add_header(self, name, value):
self._headers.setdefault(_hkey(name), []).append(_hval(value))<EOL>
Add an additional response header, not removing duplicates.
f8968:c14:m15
def iter_headers(self):
return self.headerlist<EOL>
Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.
f8968:c14:m16
@property<EOL><INDENT>def headerlist(self):<DEDENT>
out = []<EOL>headers = list(self._headers.items())<EOL>if '<STR_LIT:Content-Type>' not in self._headers:<EOL><INDENT>headers.append(('<STR_LIT:Content-Type>', [self.default_content_type]))<EOL><DEDENT>if self._status_code in self.bad_headers:<EOL><INDENT>bad_headers = self.bad_headers[self._status_code]<EOL>headers = [h for h in headers if h[<NUM_LIT:0>] not in bad_headers]<EOL><DEDENT>out += [(name, val) for (name, vals) in headers for val in vals]<EOL>if self._cookies:<EOL><INDENT>for c in self._cookies.values():<EOL><INDENT>out.append(('<STR_LIT>', _hval(c.OutputString())))<EOL><DEDENT><DEDENT>if py3k:<EOL><INDENT>out = [(k, v.encode('<STR_LIT:utf8>').decode('<STR_LIT>')) for (k, v) in out]<EOL><DEDENT>return out<EOL>
WSGI conform list of (header, value) tuples.
f8968:c14:m17
@property<EOL><INDENT>def charset(self, default='<STR_LIT>'):<DEDENT>
if '<STR_LIT>' in self.content_type:<EOL><INDENT>return self.content_type.split('<STR_LIT>')[-<NUM_LIT:1>].split('<STR_LIT:;>')[<NUM_LIT:0>].strip()<EOL><DEDENT>return default<EOL>
Return the charset specified in the content-type header (default: utf8).
f8968:c14:m18
def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options):
if not self._cookies:<EOL><INDENT>self._cookies = SimpleCookie()<EOL><DEDENT>Morsel._reserved['<STR_LIT>'] = '<STR_LIT>'<EOL>if secret:<EOL><INDENT>if not isinstance(value, basestring):<EOL><INDENT>depr(<NUM_LIT:0>, <NUM_LIT>, "<STR_LIT>"<EOL>"<STR_LIT>", "<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>encoded = base64.b64encode(pickle.dumps([name, value], -<NUM_LIT:1>))<EOL>sig = base64.b64encode(hmac.new(tob(secret), encoded,<EOL>digestmod=digestmod).digest())<EOL>value = touni(tob('<STR_LIT:!>') + sig + tob('<STR_LIT:?>') + encoded)<EOL><DEDENT>elif not isinstance(value, basestring):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(name) + len(value) > <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._cookies[name] = value<EOL>for key, value in options.items():<EOL><INDENT>if key == '<STR_LIT>':<EOL><INDENT>if isinstance(value, timedelta):<EOL><INDENT>value = value.seconds + value.days * <NUM_LIT> * <NUM_LIT><EOL><DEDENT><DEDENT>if key == '<STR_LIT>':<EOL><INDENT>if isinstance(value, (datedate, datetime)):<EOL><INDENT>value = value.timetuple()<EOL><DEDENT>elif isinstance(value, (int, float)):<EOL><INDENT>value = time.gmtime(value)<EOL><DEDENT>value = time.strftime("<STR_LIT>", value)<EOL><DEDENT>if key == '<STR_LIT>' and value.lower() not in ('<STR_LIT>', '<STR_LIT:strict>'):<EOL><INDENT>raise CookieError("<STR_LIT>" % (key,))<EOL><DEDENT>if key in ('<STR_LIT>', '<STR_LIT>') and not value:<EOL><INDENT>continue<EOL><DEDENT>self._cookies[name][key.replace('<STR_LIT:_>', '<STR_LIT:->')] = value<EOL><DEDENT>
Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that are supported by :class:`cookie.Morsel`, including: :param max_age: maximum age in seconds. (default: None) :param expires: a datetime object or UNIX timestamp. (default: None) :param domain: the domain that is allowed to read the cookie. (default: current domain) :param path: limits the cookie to a given path (default: current path) :param secure: limit the cookie to HTTPS connections (default: off). :param httponly: prevents client-side javascript to read this cookie (default: off, requires Python 2.6 or newer). :param same_site: disables third-party use for a cookie. Allowed attributes: `lax` and `strict`. In strict mode the cookie will never be sent. In lax mode the cookie is only sent with a top-level GET request. If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: 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 unpickeld. 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.
f8968:c14:m19
def delete_cookie(self, key, **kwargs):
kwargs['<STR_LIT>'] = -<NUM_LIT:1><EOL>kwargs['<STR_LIT>'] = <NUM_LIT:0><EOL>self.set_cookie(key, '<STR_LIT>', **kwargs)<EOL>
Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie.
f8968:c14:m20
def __init__(self, name, impmask):
self.name = name<EOL>self.impmask = impmask<EOL>self.module = sys.modules.setdefault(name, imp.new_module(name))<EOL>self.module.__dict__.update({<EOL>'<STR_LIT>': __file__,<EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': self<EOL>})<EOL>sys.meta_path.append(self)<EOL>
Create a virtual package that redirects imports (see PEP 302).
f8968:c22:m0
def get(self, key, default=None, index=-<NUM_LIT:1>, type=None):
try:<EOL><INDENT>val = self.dict[key][index]<EOL>return type(val) if type else val<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>return default<EOL>
Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. :param 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.
f8968:c23:m8
def append(self, key, value):
self.dict.setdefault(key, []).append(value)<EOL>
Add a new value to the list of values for this key.
f8968:c23:m9
def replace(self, key, value):
self.dict[key] = [value]<EOL>
Replace the list of values with a single value.
f8968:c23:m10
def getall(self, key):
return self.dict.get(key) or []<EOL>
Return a (possibly empty) list of values for a key.
f8968:c23:m11
def decode(self, encoding=None):
copy = FormsDict()<EOL>enc = copy.input_encoding = encoding or self.input_encoding<EOL>copy.recode_unicode = False<EOL>for key, value in self.allitems():<EOL><INDENT>copy.append(self._fix(key, enc), self._fix(value, enc))<EOL><DEDENT>return copy<EOL>
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.
f8968:c24:m1
def getunicode(self, name, default=None, encoding=None):
try:<EOL><INDENT>return self._fix(self[name], encoding)<EOL><DEDENT>except (UnicodeError, KeyError):<EOL><INDENT>return default<EOL><DEDENT>
Return the value as a unicode string, or the default.
f8968:c24:m2
def _ekey(self, key):
key = key.replace('<STR_LIT:->', '<STR_LIT:_>').upper()<EOL>if key in self.cgikeys:<EOL><INDENT>return key<EOL><DEDENT>return '<STR_LIT>' + key<EOL>
Translate header field name to CGI/WSGI environ key.
f8968:c26:m1
def raw(self, key, default=None):
return self.environ.get(self._ekey(key), default)<EOL>
Return the header value as is (may be bytes or unicode).
f8968:c26:m2
def load_module(self, path, squash=True):
config_obj = load(path)<EOL>obj = {key: getattr(config_obj, key) for key in dir(config_obj)<EOL>if key.isupper()}<EOL>if squash:<EOL><INDENT>self.load_dict(obj)<EOL><DEDENT>else:<EOL><INDENT>self.update(obj)<EOL><DEDENT>return self<EOL>
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'}} :param squash: If true (default), dictionary values are assumed to represent namespaces (see :meth:`load_dict`).
f8968:c27:m1
def load_config(self, filename, **options):
options.setdefault('<STR_LIT>', True)<EOL>if py3k:<EOL><INDENT>options.setdefault('<STR_LIT>',<EOL>configparser.ExtendedInterpolation())<EOL><DEDENT>conf = configparser.ConfigParser(**options)<EOL>conf.read(filename)<EOL>for section in conf.sections():<EOL><INDENT>for key in conf.options(section):<EOL><INDENT>value = conf.get(section, key)<EOL>if section not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>key = section + '<STR_LIT:.>' + key<EOL><DEDENT>self[key.lower()] = value<EOL><DEDENT><DEDENT>return self<EOL>
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. :param filename: The path of a config file, or a list of paths. :param options: All keyword parameters are passed to the underlying :class:`python:configparser.ConfigParser` constructor call.
f8968:c27:m2
def load_dict(self, source, namespace='<STR_LIT>'):
for key, value in source.items():<EOL><INDENT>if isinstance(key, basestring):<EOL><INDENT>nskey = (namespace + '<STR_LIT:.>' + key).strip('<STR_LIT:.>')<EOL>if isinstance(value, dict):<EOL><INDENT>self.load_dict(value, namespace=nskey)<EOL><DEDENT>else:<EOL><INDENT>self[nskey] = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % type(key))<EOL><DEDENT><DEDENT>return self<EOL>
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'}
f8968:c27:m3
def update(self, *a, **ka):
prefix = '<STR_LIT>'<EOL>if a and isinstance(a[<NUM_LIT:0>], basestring):<EOL><INDENT>prefix = a[<NUM_LIT:0>].strip('<STR_LIT:.>') + '<STR_LIT:.>'<EOL>a = a[<NUM_LIT:1>:]<EOL><DEDENT>for key, value in dict(*a, **ka).items():<EOL><INDENT>self[prefix + key] = value<EOL><DEDENT>
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')
f8968:c27:m4
def _set_virtual(self, key, value):
if key in self and key not in self._virtual_keys:<EOL><INDENT>return <EOL><DEDENT>self._virtual_keys.add(key)<EOL>if key in self and self[key] is not value:<EOL><INDENT>self._on_change(key, value)<EOL><DEDENT>dict.__setitem__(self, key, value)<EOL>for overlay in self._iter_overlays():<EOL><INDENT>overlay._set_virtual(key, value)<EOL><DEDENT>
Recursively set or update virtual keys. Do nothing if non-virtual value is present.
f8968:c27:m8
def _delete_virtual(self, key):
if key not in self._virtual_keys:<EOL><INDENT>return <EOL><DEDENT>if key in self:<EOL><INDENT>self._on_change(key, None)<EOL><DEDENT>dict.__delitem__(self, key)<EOL>self._virtual_keys.discard(key)<EOL>for overlay in self._iter_overlays():<EOL><INDENT>overlay._delete_virtual(key)<EOL><DEDENT>
Recursively delete virtual entry. Do nothing if key is not virtual.
f8968:c27:m9
def meta_get(self, key, metafield, default=None):
return self._meta.get(key, {}).get(metafield, default)<EOL>
Return the value of a meta field for a key.
f8968:c27:m12
def meta_set(self, key, metafield, value):
self._meta.setdefault(key, {})[metafield] = value<EOL>
Set the meta field for a key to a new value.
f8968:c27:m13
def meta_list(self, key):
return self._meta.get(key, {}).keys()<EOL>
Return an iterable of meta field names defined for a key.
f8968:c27:m14
def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET):
if default is not _UNSET:<EOL><INDENT>self.setdefault(key, default)<EOL><DEDENT>if help is not _UNSET:<EOL><INDENT>self.meta_set(key, '<STR_LIT>', help)<EOL><DEDENT>if validate is not _UNSET:<EOL><INDENT>self.meta_set(key, '<STR_LIT>', validate)<EOL><DEDENT>
(Unstable) Shortcut for plugins to define own config parameters.
f8968:c27:m15
def _make_overlay(self):
<EOL>self._overlays[:] = [ref for ref in self._overlays if ref() is not None]<EOL>overlay = ConfigDict()<EOL>overlay._meta = self._meta<EOL>overlay._source = self<EOL>self._overlays.append(weakref.ref(overlay))<EOL>for key in self:<EOL><INDENT>overlay._set_virtual(key, self[key])<EOL><DEDENT>return overlay<EOL>
(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
f8968:c27:m17
def __call__(self):
return self.default<EOL>
Return the current default application.
f8968:c28:m0
def push(self, value=None):
if not isinstance(value, Bottle):<EOL><INDENT>value = Bottle()<EOL><DEDENT>self.append(value)<EOL>return value<EOL>
Add a new :class:`Bottle` instance to the stack
f8968:c28:m1
def add_path(self, path, base=None, index=None, create=False):
base = os.path.abspath(os.path.dirname(base or self.base))<EOL>path = os.path.abspath(os.path.join(base, os.path.dirname(path)))<EOL>path += os.sep<EOL>if path in self.path:<EOL><INDENT>self.path.remove(path)<EOL><DEDENT>if create and not os.path.isdir(path):<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>if index is None:<EOL><INDENT>self.path.append(path)<EOL><DEDENT>else:<EOL><INDENT>self.path.insert(index, path)<EOL><DEDENT>self.cache.clear()<EOL>return os.path.exists(path)<EOL>
Add a new path to the list of search paths. Return False if the path does not exist. :param 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. :param base: Path used to absolutize relative search paths. Defaults to :attr:`base` which defaults to ``os.getcwd()``. :param 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__)
f8968:c31:m1
def __iter__(self):
search = self.path[:]<EOL>while search:<EOL><INDENT>path = search.pop()<EOL>if not os.path.isdir(path): continue<EOL>for name in os.listdir(path):<EOL><INDENT>full = os.path.join(path, name)<EOL>if os.path.isdir(full): search.append(full)<EOL>else: yield full<EOL><DEDENT><DEDENT>
Iterate over all existing files in all registered paths.
f8968:c31:m2