desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Protect keys, items, and values.'
def __setattr__(self, name, value):
if (not ('_att_dict' in self.__dict__)): object.__setattr__(self, name, value) else: try: fun = self._att_dict[name] except KeyError: OrderedDict.__setattr__(self, name, value) else: fun(value)
'True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()'
def should_wrap(self):
return (self.convert or self.strip or self.autoreset)
'Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.'
def write_and_convert(self, text):
cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): (start, end) = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
'Add a filter. The provided function is called with the configuration string as parameter and must return a (regexp, to_python, to_url) tuple. The first element is a string, the last two are callables or None.'
def add_filter(self, name, func):
self.filters[name] = func
'Add a new rule or replace the target for an existing rule.'
def add(self, rule, method, target, name=None):
anons = 0 keys = [] pattern = '' filters = [] builder = [] is_static = True for (key, mode, conf) in self._itertokens(rule): if mode: is_static = False if (mode == 'default'): mode = self.default_filter (mask, in_filter, out_filter) = self.filters[mode](conf) if (not key): pattern += ('(?:%s)' % mask) key = ('anon%d' % anons) anons += 1 else: pattern += ('(?P<%s>%s)' % (key, mask)) keys.append(key) if in_filter: filters.append((key, in_filter)) builder.append((key, (out_filter or str))) elif key: pattern += re.escape(key) builder.append((None, key)) self.builder[rule] = builder if name: self.builder[name] = builder if (is_static and (not self.strict_order)): self.static.setdefault(method, {}) self.static[method][self.build(rule)] = (target, None) return try: re_pattern = re.compile(('^(%s)$' % pattern)) re_match = re_pattern.match except re.error: raise RouteSyntaxError(('Could not add Route: %s (%s)' % (rule, _e()))) if filters: def getargs(path): url_args = re_match(path).groupdict() for (name, wildcard_filter) in filters: try: url_args[name] = wildcard_filter(url_args[name]) except ValueError: raise HTTPError(400, 'Path has wrong format.') return url_args elif re_pattern.groupindex: def getargs(path): return re_match(path).groupdict() else: getargs = None flatpat = _re_flatten(pattern) whole_rule = (rule, flatpat, target, getargs) if ((flatpat, method) in self._groups): if DEBUG: msg = 'Route <%s %s> overwrites a previously defined route' warnings.warn((msg % (method, rule)), RuntimeWarning) self.dyna_routes[method][self._groups[(flatpat, method)]] = whole_rule else: self.dyna_routes.setdefault(method, []).append(whole_rule) self._groups[(flatpat, method)] = (len(self.dyna_routes[method]) - 1) self._compile(method)
'Build an URL by filling the wildcards in a rule.'
def build(self, _name, *anons, **query):
builder = self.builder.get(_name) if (not builder): raise RouteBuildError('No route with that name.', _name) try: for (i, value) in enumerate(anons): query[('anon%d' % i)] = value url = ''.join([(f(query.pop(n)) if n else f) for (n, f) in builder]) return (url if (not query) else ((url + '?') + urlencode(query))) except KeyError: raise RouteBuildError(('Missing URL argument: %r' % _e().args[0]))
'Return a (target, url_args) tuple or raise HTTPError(400/404/405).'
def match(self, environ):
verb = environ['REQUEST_METHOD'].upper() path = (environ['PATH_INFO'] or '/') if (verb == 'HEAD'): methods = ['PROXY', verb, 'GET', 'ANY'] else: methods = ['PROXY', verb, 'ANY'] for method in methods: if ((method in self.static) and (path in self.static[method])): (target, getargs) = self.static[method][path] return (target, (getargs(path) if getargs else {})) elif (method in self.dyna_regexes): for (combined, rules) in self.dyna_regexes[method]: match = combined(path) if match: (target, getargs) = rules[(match.lastindex - 1)] return (target, (getargs(path) if getargs else {})) allowed = set([]) nocheck = set(methods) for method in (set(self.static) - nocheck): if (path in self.static[method]): allowed.add(verb) for method in ((set(self.dyna_regexes) - allowed) - nocheck): for (combined, rules) in self.dyna_regexes[method]: match = combined(path) if match: allowed.add(method) if allowed: allow_header = ','.join(sorted(allowed)) raise HTTPError(405, 'Method not allowed.', Allow=allow_header) raise HTTPError(404, ('Not found: ' + repr(path)))
'The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.'
@cached_property def call(self):
return self._make_callback()
'Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.'
def reset(self):
self.__dict__.pop('call', None)
'Do all on-demand work immediately (useful for debugging).'
def prepare(self):
self.call
'Yield all Plugins affecting this route.'
def all_plugins(self):
unique = set() for p in reversed((self.app.plugins + self.plugins)): if (True in self.skiplist): break name = getattr(p, 'name', False) if (name and ((name in self.skiplist) or (name in unique))): continue if ((p in self.skiplist) or (type(p) in self.skiplist)): continue if name: unique.add(name) (yield p)
'Return the callback. If the callback is a decorated function, try to recover the original function.'
def get_undecorated_callback(self):
func = self.callback func = getattr(func, ('__func__' if py3k else 'im_func'), func) closure_attr = ('__closure__' if py3k else 'func_closure') while (hasattr(func, closure_attr) and getattr(func, closure_attr)): attributes = getattr(func, closure_attr) func = attributes[0].cell_contents if (not isinstance(func, FunctionType)): func = filter((lambda x: isinstance(x, FunctionType)), map((lambda x: x.cell_contents), attributes)) func = list(func)[0] return func
'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.'
def get_callback_args(self):
return getargspec(self.get_undecorated_callback())[0]
'Lookup a config field and return its value, first checking the route.config, then route.app.config.'
def get_config(self, key, default=None):
for conf in (self.config, self.app.config): if (key in conf): return conf[key] return default
'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.'
def add_hook(self, name, func):
if (name in self.__hook_reversed): self._hooks[name].insert(0, func) else: self._hooks[name].append(func)
'Remove a callback from a hook.'
def remove_hook(self, name, func):
if ((name in self._hooks) and (func in self._hooks[name])): self._hooks[name].remove(func) return True
'Trigger a hook and return a list of results.'
def trigger_hook(self, __name, *args, **kwargs):
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
'Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.'
def hook(self, name):
def decorator(func): self.add_hook(name, func) return func return decorator
'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):
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: _raise(*exc_info) rs.status = status for (name, value) in headerlist: rs.add_header(name, value) return rs.body.append body = app(request.environ, start_response) rs.body = (itertools.chain(rs.body, body) if rs.body else 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)
'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):
if isinstance(routes, Bottle): routes = routes.routes for route in routes: self.add_route(route)
'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):
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
'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):
(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
'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):
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')
'Close the application and all installed plugins.'
def close(self):
for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close()
'Calls :func:`run` with the same parameters.'
def run(self, **kwargs):
run(self, **kwargs)
'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):
return self.router.match(environ)
'Return a string that matches a named route'
def get_url(self, routename, **kargs):
scriptname = (request.environ.get('SCRIPT_NAME', '').strip('/') + '/') location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location)
'Add a route object, but do not change the :data:`Route.app` attribute.'
def add_route(self, route):
self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
'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):
if callable(path): (path, callback) = (None, path) plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): 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)
'Equals :meth:`route`.'
def get(self, path=None, method='GET', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``POST`` method parameter.'
def post(self, path=None, method='POST', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``PUT`` method parameter.'
def put(self, path=None, method='PUT', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``DELETE`` method parameter.'
def delete(self, path=None, method='DELETE', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``PATCH`` method parameter.'
def patch(self, path=None, method='PATCH', **options):
return self.route(path, method, **options)
'Decorator: Register an output handler for a HTTP error code'
def error(self, code=500):
def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper
'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'
def _cast(self, out, peek=None):
if (not out): if ('Content-Length' not in response): response['Content-Length'] = 0 return [] if (isinstance(out, (tuple, list)) and isinstance(out[0], (bytes, unicode))): out = out[0][0:0].join(out) if isinstance(out, unicode): out = out.encode(response.charset) if isinstance(out, bytes): if ('Content-Length' not in response): response['Content-Length'] = len(out) return [out] if isinstance(out, HTTPError): out.apply(response) out = self.error_handler.get(out.status_code, self.default_error_handler)(out) return self._cast(out) if isinstance(out, HTTPResponse): out.apply(response) return self._cast(out.body) if hasattr(out, 'read'): if ('wsgi.file_wrapper' in request.environ): return request.environ['wsgi.file_wrapper'](out) elif (hasattr(out, 'close') or (not hasattr(out, '__iter__'))): return WSGIFileWrapper(out) try: iout = iter(out) first = next(iout) while (not first): first = next(iout) except StopIteration: return self._cast('') except HTTPResponse: first = _e() except (KeyboardInterrupt, SystemExit, MemoryError): raise except: if (not self.catchall): raise first = HTTPError(500, 'Unhandled exception', _e(), format_exc()) if isinstance(first, HTTPResponse): return self._cast(first) elif isinstance(first, bytes): new_iter = itertools.chain([first], iout) elif isinstance(first, unicode): encoder = (lambda x: x.encode(response.charset)) new_iter = imap(encoder, itertools.chain([first], iout)) else: msg = ('Unsupported response type: %s' % type(first)) return self._cast(HTTPError(500, msg)) if hasattr(out, 'close'): new_iter = _closeiter(new_iter, out.close) return new_iter
'The bottle WSGI-interface.'
def wsgi(self, environ, start_response):
try: out = self._cast(self._handle(environ)) 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: 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)]
'Each instance of :class:\'Bottle\' is a WSGI application.'
def __call__(self, environ, start_response):
return self.wsgi(environ, start_response)
'Use this application as default for all module-level shortcuts.'
def __enter__(self):
default_app.push(self) return self
'Wrap a WSGI environ dictionary.'
def __init__(self, environ=None):
self.environ = ({} if (environ is None) else environ) self.environ['bottle.request'] = self
'Bottle application handling this request.'
@DictProperty('environ', 'bottle.app', read_only=True) def app(self):
raise RuntimeError('This request is not connected to an application.')
'The bottle :class:`Route` object that matches this request.'
@DictProperty('environ', 'bottle.route', read_only=True) def route(self):
raise RuntimeError('This request is not connected to a route.')
'The arguments extracted from the URL.'
@DictProperty('environ', 'route.url_args', read_only=True) def url_args(self):
raise RuntimeError('This request is not connected to a route.')
'The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case).'
@property def path(self):
return ('/' + self.environ.get('PATH_INFO', '').lstrip('/'))
'The ``REQUEST_METHOD`` value as an uppercase string.'
@property def method(self):
return self.environ.get('REQUEST_METHOD', 'GET').upper()
'A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers.'
@DictProperty('environ', 'bottle.request.headers', read_only=True) def headers(self):
return WSGIHeaderDict(self.environ)
'Return the value of a request header, or a given default value.'
def get_header(self, name, default=None):
return self.headers.get(name, default)
'Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies.'
@DictProperty('environ', 'bottle.request.cookies', read_only=True) def cookies(self):
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values() return FormsDict(((c.key, c.value) for c in cookies))
'Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.'
def get_cookie(self, key, default=None, secret=None):
value = self.cookies.get(key) if (secret and value): dec = cookie_decode(value, secret) return (dec[1] if (dec and (dec[0] == key)) else default) return (value or default)
'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`.'
@DictProperty('environ', 'bottle.request.query', read_only=True) def query(self):
get = self.environ['bottle.get'] = FormsDict() pairs = _parse_qsl(self.environ.get('QUERY_STRING', '')) for (key, value) in pairs: get[key] = value return get
'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`.'
@DictProperty('environ', 'bottle.request.forms', read_only=True) def forms(self):
forms = FormsDict() for (name, item) in self.POST.allitems(): if (not isinstance(item, FileUpload)): forms[name] = item return forms
'A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.'
@DictProperty('environ', 'bottle.request.params', read_only=True) def params(self):
params = FormsDict() for (key, value) in self.query.allitems(): params[key] = value for (key, value) in self.forms.allitems(): params[key] = value return params
'File uploads parsed from `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`FileUpload`.'
@DictProperty('environ', 'bottle.request.files', read_only=True) def files(self):
files = FormsDict() for (name, item) in self.POST.allitems(): if isinstance(item, FileUpload): files[name] = item return files
'If the ``Content-Type`` header is ``application/json``, 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.'
@DictProperty('environ', 'bottle.request.json', read_only=True) def json(self):
ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0] if (ctype == 'application/json'): b = self._get_body_string() if (not b): return None try: return json_loads(b) except (ValueError, TypeError): raise HTTPError(400, 'Invalid JSON') return None
'read body until content-length or MEMFILE_MAX into a string. Raise HTTPError(413) on requests that are to large.'
def _get_body_string(self):
clen = self.content_length if (clen > self.MEMFILE_MAX): raise HTTPError(413, 'Request entity too large') if (clen < 0): clen = (self.MEMFILE_MAX + 1) data = self.body.read(clen) if (len(data) > self.MEMFILE_MAX): raise HTTPError(413, 'Request entity too large') return data
'The HTTP request body as a seek-able file-like object. Depending on :attr:`MEMFILE_MAX`, this is either a temporary file or a :class:`io.BytesIO` instance. Accessing this property for the first time reads and replaces the ``wsgi.input`` environ variable. Subsequent accesses just do a `seek(0)` on the file object.'
@property def body(self):
self._body.seek(0) return self._body
'True if Chunked transfer encoding was.'
@property def chunked(self):
return ('chunked' in self.environ.get('HTTP_TRANSFER_ENCODING', '').lower())
'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).'
@DictProperty('environ', 'bottle.request.post', read_only=True) def POST(self):
post = FormsDict() if (not self.content_type.startswith('multipart/')): pairs = _parse_qsl(tonat(self._get_body_string(), 'latin1')) for (key, value) in pairs: post[key] = value return post safe_env = {'QUERY_STRING': ''} for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if (key in self.environ): safe_env[key] = self.environ[key] args = dict(fp=self.body, environ=safe_env, keep_blank_values=True) if py31: args['fp'] = NCTextIOWrapper(args['fp'], encoding='utf8', newline='\n') elif py3k: args['encoding'] = 'utf8' data = cgi.FieldStorage(**args) self['_cgi.FieldStorage'] = data data = (data.list or []) for item in data: if item.filename: post[item.name] = FileUpload(item.file, item.name, item.filename, item.headers) else: post[item.name] = item.value return post
'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.'
@property def url(self):
return self.urlparts.geturl()
'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.'
@DictProperty('environ', 'bottle.request.urlparts', read_only=True) def urlparts(self):
env = self.environ http = (env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http')) host = (env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')) if (not host): host = env.get('SERVER_NAME', '127.0.0.1') port = env.get('SERVER_PORT') if (port and (port != ('80' if (http == 'http') else '443'))): host += (':' + port) path = urlquote(self.fullpath) return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')
'Request path including :attr:`script_name` (if present).'
@property def fullpath(self):
return urljoin(self.script_name, self.path.lstrip('/'))
'The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string.'
@property def query_string(self):
return self.environ.get('QUERY_STRING', '')
'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.'
@property def script_name(self):
script_name = self.environ.get('SCRIPT_NAME', '').strip('/') return ((('/' + script_name) + '/') if script_name else '/')
'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)'
def path_shift(self, shift=1):
(script, path) = path_shift(self.environ.get('SCRIPT_NAME', '/'), self.path, shift) (self['SCRIPT_NAME'], self['PATH_INFO']) = (script, path)
'The request body length as an integer. The client is responsible to set this header. Otherwise, the real length of the body is unknown and -1 is returned. In this case, :attr:`body` will be empty.'
@property def content_length(self):
return int((self.environ.get('CONTENT_LENGTH') or (-1)))
'The Content-Type header as a lowercase-string (default: empty).'
@property def content_type(self):
return self.environ.get('CONTENT_TYPE', '').lower()
'True if the request was triggered by a XMLHttpRequest. This only works with JavaScript libraries that support the `X-Requested-With` header (most of the popular libraries do).'
@property def is_xhr(self):
requested_with = self.environ.get('HTTP_X_REQUESTED_WITH', '') return (requested_with.lower() == 'xmlhttprequest')
'Alias for :attr:`is_xhr`. "Ajax" is not the right term.'
@property def is_ajax(self):
return self.is_xhr
'HTTP authentication data as a (user, password) tuple. This implementation currently supports basic (not digest) authentication only. If the authentication happened at a higher level (e.g. in the front web-server or a middleware), the password field is None, but the user field is looked up from the ``REMOTE_USER`` environ variable. On any errors, None is returned.'
@property def auth(self):
basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION', '')) if basic: return basic ruser = self.environ.get('REMOTE_USER') if ruser: return (ruser, None) return None
'A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients.'
@property def remote_route(self):
proxy = self.environ.get('HTTP_X_FORWARDED_FOR') if proxy: return [ip.strip() for ip in proxy.split(',')] remote = self.environ.get('REMOTE_ADDR') return ([remote] if remote else [])
'The client IP as a string. Note that this information can be forged by malicious clients.'
@property def remote_addr(self):
route = self.remote_route return (route[0] if route else None)
'Return a new :class:`Request` with a shallow :attr:`environ` copy.'
def copy(self):
return Request(self.environ.copy())
'Change an environ value and clear all caches that depend on it.'
def __setitem__(self, key, value):
if self.environ.get('bottle.request.readonly'): raise KeyError('The environ dictionary is read-only.') self.environ[key] = value todelete = () if (key == 'wsgi.input'): todelete = ('body', 'forms', 'files', 'params', 'post', 'json') elif (key == 'QUERY_STRING'): todelete = ('query', 'params') elif key.startswith('HTTP_'): todelete = ('headers', 'cookies') for key in todelete: self.environ.pop(('bottle.request.' + key), None)
'Search in self.environ for additional user defined attributes.'
def __getattr__(self, name):
try: var = self.environ[('bottle.request.ext.%s' % name)] return (var.__get__(self) if hasattr(var, '__get__') else var) except KeyError: raise AttributeError(('Attribute %r not defined.' % name))
'Returns a copy of self.'
def copy(self, cls=None):
cls = (cls or BaseResponse) assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict(((k, v[:]) for (k, v) in self._headers.items())) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output(header='')) return copy
'The HTTP status line as a string (e.g. ``404 Not Found``).'
@property def status_line(self):
return self._status_line
'The HTTP status code as an integer (e.g. 404).'
@property def status_code(self):
return self._status_code
'An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.'
@property def headers(self):
hdict = HeaderDict() hdict.dict = self._headers return hdict
'Return the value of a previously defined header. If there is no header with that name, return a default value.'
def get_header(self, name, default=None):
return self._headers.get(_hkey(name), [default])[(-1)]
'Create a new response header, replacing any previously defined headers with the same name.'
def set_header(self, name, value):
self._headers[_hkey(name)] = [(value if isinstance(value, unicode) else str(value))]
'Add an additional response header, not removing duplicates.'
def add_header(self, name, value):
self._headers.setdefault(_hkey(name), []).append((value if isinstance(value, unicode) else str(value)))
'Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.'
def iter_headers(self):
return self.headerlist
'WSGI conform list of (header, value) tuples.'
@property def headerlist(self):
out = [] headers = list(self._headers.items()) if ('Content-Type' not in self._headers): headers.append(('Content-Type', [self.default_content_type])) if (self._status_code in self.bad_headers): bad_headers = self.bad_headers[self._status_code] headers = [h for h in headers if (h[0] not in bad_headers)] out += [(name, val) for (name, vals) in headers for val in vals] if self._cookies: for c in self._cookies.values(): out.append(('Set-Cookie', c.OutputString())) if py3k: return [(k, v.encode('utf8').decode('latin1')) for (k, v) in out] else: return [(k, (v.encode('utf8') if isinstance(v, unicode) else v)) for (k, v) in out]
'Return the charset specified in the content-type header (default: utf8).'
@property def charset(self, default='UTF-8'):
if ('charset=' in self.content_type): return self.content_type.split('charset=')[(-1)].split(';')[0].strip() return default
'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). If neither `expires` nor `max_age` is set (default), the cookie will expire at the end of the browser session (as soon as the browser window is closed). Signed cookies may store any pickle-able object and are cryptographically signed to prevent manipulation. Keep in mind that cookies are limited to 4kb in most browsers. Warning: Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling save, not to store secret information at client side.'
def set_cookie(self, name, value, secret=None, **options):
if (not self._cookies): self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((name, value), secret)) elif (not isinstance(value, basestring)): raise TypeError('Secret key missing for non-string Cookie.') if ((len(name) + len(value)) > 3800): raise ValueError('Content does not fit into a cookie.') self._cookies[name] = value for (key, value) in options.items(): if (key == 'max_age'): if isinstance(value, timedelta): value = (value.seconds + ((value.days * 24) * 3600)) if (key == 'expires'): if isinstance(value, (datedate, datetime)): value = value.timetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) value = time.strftime('%a, %d %b %Y %H:%M:%S GMT', value) if ((key in ('secure', 'httponly')) and (not value)): continue self._cookies[name][key.replace('_', '-')] = value
'Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie.'
def delete_cookie(self, key, **kwargs):
kwargs['max_age'] = (-1) kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs)
'Create a virtual package that redirects imports (see PEP 302).'
def __init__(self, name, impmask):
self.name = name self.impmask = impmask self.module = sys.modules.setdefault(name, imp.new_module(name)) self.module.__dict__.update({'__file__': __file__, '__path__': [], '__all__': [], '__loader__': self}) sys.meta_path.append(self)
'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.'
def get(self, key, default=None, index=(-1), type=None):
try: val = self.dict[key][index] return (type(val) if type else val) except Exception: pass return default
'Add a new value to the list of values for this key.'
def append(self, key, value):
self.dict.setdefault(key, []).append(value)
'Replace the list of values with a single value.'
def replace(self, key, value):
self.dict[key] = [value]
'Return a (possibly empty) list of values for a key.'
def getall(self, key):
return (self.dict.get(key) or [])
'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.'
def decode(self, encoding=None):
copy = FormsDict() enc = copy.input_encoding = (encoding or self.input_encoding) copy.recode_unicode = False for (key, value) in self.allitems(): copy.append(self._fix(key, enc), self._fix(value, enc)) return copy
'Return the value as a unicode string, or the default.'
def getunicode(self, name, default=None, encoding=None):
try: return self._fix(self[name], encoding) except (UnicodeError, KeyError): return default
'Translate header field name to CGI/WSGI environ key.'
def _ekey(self, key):
key = key.replace('-', '_').upper() if (key in self.cgikeys): return key return ('HTTP_' + key)
'Return the header value as is (may be bytes or unicode).'
def raw(self, key, default=None):
return self.environ.get(self._ekey(key), default)
'Load values from a Python module. :param squash: Squash nested dicts into namespaces by using load_dict(), otherwise use update() Example: load_config(\'my.app.settings\', True) Example: load_config(\'my.app.settings\', False)'
def load_module(self, path, squash):
config_obj = __import__(path) obj = dict([(key, getattr(config_obj, key)) for key in dir(config_obj) if key.isupper()]) if squash: self.load_dict(obj) else: self.update(obj) return self
'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):
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
'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\'}'
def load_dict(self, source, namespace=''):
for (key, value) in source.items(): if isinstance(key, basestring): nskey = ((namespace + '.') + key).strip('.') if isinstance(value, dict): self.load_dict(value, namespace=nskey) else: self[nskey] = value else: raise TypeError(('Key has type %r (not a string)' % type(key))) return self
'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):
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
'Return the value of a meta field for a key.'
def meta_get(self, key, metafield, default=None):
return self._meta.get(key, {}).get(metafield, default)