desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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)))
'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`` envi...
@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'): t...
'Returns a copy of self.'
def copy(self):
copy = Response() copy.status = self.status copy._headers = dict(((k, v[:]) for (k, v) in self._headers.items())) return copy
'An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.'
@property def headers(self):
self.__dict__['headers'] = 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. This equals ``response[name] = value``.:param append: Do not delete previously defined headers. This can result in two (or more) headers having the same name.'
def set_header(self, name, value, append=False):
if append: self._headers.setdefault(_hkey(name), []).append(str(value)) else: self._headers[_hkey(name)] = [str(value)]
'Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.'
def iter_headers(self):
headers = self._headers.iteritems() bad_headers = self.bad_headers.get(self.status_code) if bad_headers: headers = (h for h in headers if (h[0] not in bad_headers)) for (name, values) in headers: for value in values: (yield (name, value)) if self._cookies: for c i...
'WSGI conform list of (header, value) tuples.'
@property def headerlist(self):
return list(self.iter_headers())
'Return the charset specified in the content-type header (default: utf8).'
@property def charset(self):
if ('charset=' in self.content_type): return self.content_type.split('charset=')[(-1)].split(';')[0].strip() return 'UTF-8'
'A dict-like SimpleCookie instance. This should not be used directly. See :meth:`set_cookie`.'
@property def COOKIES(self):
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') if (not self._cookies): self._cookies = SimpleCookie() return self._cookies
'Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below).:param key: the name of the cookie. :param value: the value of the cookie.:param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that ar...
def set_cookie(self, key, value, secret=None, **options):
if (not self._cookies): self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((key, value), secret)) elif (not isinstance(value, basestring)): raise TypeError('Secret key missing for non-string Cookie.') self._cookies[key] = value for (k, v) in ...
'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)
'Attach a callback to a hook.'
def add(self, name, func):
if (name not in self.hooks): raise ValueError(('Unknown hook name %s' % name)) was_empty = self._empty() self.hooks[name].append(func) if (self.app and was_empty and (not self._empty())): self.app.reset()
'Remove a callback from a hook.'
def remove(self, name, func):
if (name not in self.hooks): raise ValueError(('Unknown hook name %s' % name)) was_empty = self._empty() self.hooks[name].remove(func) if (self.app and (not was_empty) and self._empty()): self.app.reset()
'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__': '<virtual>', '__path__': [], '__all__': [], '__loader__': self}) sys.meta_path.append(self)
'Return the current value for a key. The third `index` parameter defaults to -1 (last value).'
def get(self, key, default=None, index=(-1)):
if ((key in self.dict) or (default is KeyError)): return self.dict[key][index] 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 [])
'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)
'Return the current default application.'
def __call__(self):
return self[(-1)]
'Add a new :class:`Bottle` instance to the stack'
def push(self, value=None):
if (not isinstance(value, Bottle)): value = Bottle() self.append(value) return value
'Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance variables. The lookup parameter s...
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
self.name = name self.source = (source.read() if hasattr(source, 'read') else source) self.filename = (source.filename if hasattr(source, 'filename') else None) self.lookup = map(os.path.abspath, lookup) self.encoding = encoding self.settings = self.settings.copy() self.settings.update(setti...
'Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.'
@classmethod def search(cls, name, lookup=[]):
if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfile(fname): return fname for ext in cls.extentions: if os.path.isfile(('%s.%s' % (fname, ext))): return ('%s.%s' % (fname, ext))
'This reads or sets the global settings stored in class.settings.'
@classmethod def global_config(cls, key, *args):
if args: cls.settings[key] = args[0] else: return cls.settings[key]
'Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.'
def prepare(self, **options):
raise NotImplementedError
'Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (*args) or directly, as keywords (**kwargs).'
def render(self, *args, **kwargs):
raise NotImplementedError
'This matches comments and all kinds of quoted strings but does NOT match comments (#...) within quoted strings. (trust me)'
@lazy_attribute def re_pytokens(cls):
return re.compile('\n (\'\'(?!\')|""(?!")|\'{6}|"{6} # Empty strings (all 4 types)\n |\'(?:[^\\\\\']|\\\\.)+?\' # Single quotes (\')\n ...
'Removes comments (#...) from python code.'
@classmethod def split_comment(cls, code):
if ('#' not in code): return code subf = (lambda m: ('' if (m.group(0)[0] == '#') else m.group(0))) return re.sub(cls.re_pytokens, subf, code)
'Render the template using keyword arguments as local variables.'
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg) stdout = [] self.execute(stdout, kwargs) return ''.join(stdout)
'Add a new route or replace the target for an existing route.'
def add(self, rule, method, target, name=None):
if (rule in self.routes): self.routes[rule][method.upper()] = target else: self.routes[rule] = {method.upper(): target} self.rules.append(rule) if (self.static or self.dynamic): (self.static, self.dynamic) = ({}, {}) if name: self.named[name] = (rule, None...
'Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.'
def build(self, _name, *anon, **args):
if (_name not in self.named): raise RouteBuildError('No route with that name.', _name) (rule, pairs) = self.named[_name] if (not pairs): token = self.syntax.split(rule) parts = [p.replace('\\:', ':') for p in token[::3]] names = token[1::3] if (len(parts) ...
'Return a (target, url_agrs) tuple or raise HTTPError(404/405).'
def match(self, environ):
(targets, urlargs) = self._match_path(environ) if (not targets): raise HTTPError(404, ('Not found: ' + repr(environ['PATH_INFO']))) method = environ['REQUEST_METHOD'].upper() if (method in targets): return (targets[method], urlargs) if ((method == 'HEAD') and ('GET' in targets)...
'Optimized PATH_INFO matcher.'
def _match_path(self, environ):
path = (environ['PATH_INFO'] or '/') match = self.static.get(path) if match: return (match, {}) for (combined, rules) in self.dynamic: match = combined.match(path) if (not match): continue (gpat, match) = rules[(match.lastindex - 1)] return (match, (gp...
'Prepare static and dynamic search structures.'
def _compile(self):
self.static = {} self.dynamic = [] def fpat_sub(m): return (m.group(0) if (len(m.group(1)) % 2) else (m.group(1) + '(?:')) for rule in self.rules: target = self.routes[rule] if (not self.syntax.search(rule)): self.static[rule.replace('\\:', ':')] = target ...
'Return a regular expression with named groups for each wildcard.'
def _compile_pattern(self, rule):
out = '' for (i, part) in enumerate(self.syntax.split(rule)): if ((i % 3) == 0): out += re.escape(part.replace('\\:', ':')) elif ((i % 3) == 1): out += (('(?P<%s>' % part) if part else '(?:') else: out += ('%s)' % (part or '[^/]+')) return re.compi...
'Create a new bottle instance. You usually don\'t do that. Use `bottle.app.push()` instead.'
def __init__(self, catchall=True, autojson=True, config=None):
self.routes = [] self.router = Router() self.ccache = {} self.plugins = [] self.mounts = {} self.error_handler = {} self.catchall = catchall self.config = (config or {}) self.serve = True self.hooks = self.install(HooksPlugin()) if autojson: self.install(JSONPlugin())...
'Mount an application to a specific URL prefix. The prefix is added to SCIPT_PATH and removed from PATH_INFO before the sub-application is called.:param app: an instance of :class:`Bottle`.:param prefix: path prefix used as a mount-point. All other parameters are passed to the underlying :meth:`route` call.'
def mount(self, app, prefix, **options):
if (not isinstance(app, Bottle)): raise TypeError('Only Bottle instances are supported for now.') prefix = '/'.join(filter(None, prefix.split('/'))) if (not prefix): raise TypeError('Empty prefix. Perhaps you want a merge()?') for other in self.mounts:...
'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. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching ``name`` attribute. Pass ``True`` to remove all plugins. The list of affected plugins is returned.'
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(plugi...
'Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.'
def reset(self, id=None):
if (id is None): self.ccache.clear() else: self.ccache.pop(id, None) if DEBUG: for route in self.routes: if (route['id'] not in self.ccache): self.ccache[route['id']] = self._build_callback(route)
'Close the application and all installed plugins.'
def close(self):
for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
'(deprecated) Search for a matching route and return a (callback, urlargs) tuple. The first element is the associated route callback with plugins applied. The second value is a dictionary with parameters extracted from the URL. The :class:`Router` raises :exc:`HTTPError` (404/405) on a non-match.'
def match(self, environ):
depr('This method will change semantics in 0.10.') return self._match(environ)
'Apply plugins to a route and return a new callable.'
def _build_callback(self, config):
wrapped = config['callback'] plugins = (self.plugins + config['apply']) skip = config['skip'] try: for plugin in reversed(plugins): if (True in skip): break if ((plugin in skip) or (type(plugin) in skip)): continue if (getattr(p...
'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)
'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 ...
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): for rule in (makelist(path) or yieldroutes(callback)): for verb in makelist(method): verb = verb.upper() cfg = dict(...
'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)
'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
'Return a decorator that attaches a callback to a hook.'
def hook(self, name):
def wrapper(func): self.hooks.add(name, func) return func return wrapper
'(deprecated) Execute the first matching route callback and return the result. :exc:`HTTPResponse` exceptions are caught and returned. If :attr:`Bottle.catchall` is true, other exceptions are caught as well and returned as :exc:`HTTPError` instances (500).'
def handle(self, path, method='GET'):
depr('This method will change semantics in 0.10. Try to avoid it.') if isinstance(path, dict): return self._handle(path) return self._handle({'PATH_INFO': path, 'REQUEST_METHOD': method.upper()})
'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, request, response, peek=None):
if (not out): 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): response['Co...
'The bottle WSGI-interface.'
def wsgi(self, environ, start_response):
try: environ['bottle.app'] = self request.bind(environ) response.bind() out = self._cast(self._handle(environ), request, response) if ((response.status_code in (100, 101, 204, 304)) or (request.method == 'HEAD')): if hasattr(out, 'close'): out.clos...
'Wrap a WSGI environ dictionary.'
def __init__(self, environ):
self.environ = environ environ['bottle.request'] = self
'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)
'Cookies parsed into a dictionary. 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):
raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE', '')) cookies = {} for cookie in raw_dict.itervalues(): cookies[cookie.key] = cookie.value return 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:`MultiDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`.'
@DictProperty('environ', 'bottle.request.query', read_only=True) def query(self):
data = parse_qs(self.query_string, keep_blank_values=True) get = self.environ['bottle.get'] = MultiDict() for (key, values) in data.iteritems(): for value in values: 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:`MultiDict`. 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 = MultiDict() for (name, item) in self.POST.iterallitems(): if (not hasattr(item, 'filename')): forms[name] = item return forms
'A :class:`MultiDict` 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 = MultiDict() for (key, value) in self.query.iterallitems(): params[key] = value for (key, value) in self.forms.iterallitems(): params[key] = value return params
'File uploads parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`cgi.FieldStorage`. The most important attributes are: filename The filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored...
@DictProperty('environ', 'bottle.request.files', read_only=True) def files(self):
files = MultiDict() for (name, item) in self.POST.iterallitems(): if hasattr(item, 'filename'): 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.'
@DictProperty('environ', 'bottle.request.json', read_only=True) def json(self):
if ((self.environ.get('CONTENT_TYPE') == 'application/json') and (0 < self.content_length < self.MEMFILE_MAX)): return json_loads(self.body.read(self.MEMFILE_MAX)) return None
'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
'The values of :attr:`forms` and :attr:`files` combined into a single :class:`MultiDict`. 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 = MultiDict() safe_env = {'QUERY_STRING': ''} for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if (key in self.environ): safe_env[key] = self.environ[key] if NCTextIOWrapper: fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n') else: ...
'Alias for :attr:`cookies` (deprecated).'
@property def COOKIES(self):
depr('BaseRequest.COOKIES was renamed to BaseRequest.cookies (lowercase).') return self.cookies
'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('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'))): ...
'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 property returns an empty string, or a path 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 = self.environ.get('SCRIPT_NAME', '/') (self['SCRIPT_NAME'], self['PATH_INFO']) = path_shift(script, self.path, shift)
'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)))
'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`` envi...
@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'): t...
'Returns a copy of self.'
def copy(self):
copy = Response() copy.status = self.status copy._headers = dict(((k, v[:]) for (k, v) in self._headers.items())) return copy
'An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.'
@property def headers(self):
self.__dict__['headers'] = 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. This equals ``response[name] = value``.:param append: Do not delete previously defined headers. This can result in two (or more) headers having the same name.'
def set_header(self, name, value, append=False):
if append: self._headers.setdefault(_hkey(name), []).append(str(value)) else: self._headers[_hkey(name)] = [str(value)]
'Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.'
def iter_headers(self):
headers = self._headers.iteritems() bad_headers = self.bad_headers.get(self.status_code) if bad_headers: headers = (h for h in headers if (h[0] not in bad_headers)) for (name, values) in headers: for value in values: (yield (name, value)) if self._cookies: for c i...
'WSGI conform list of (header, value) tuples.'
@property def headerlist(self):
return list(self.iter_headers())
'Return the charset specified in the content-type header (default: utf8).'
@property def charset(self):
if ('charset=' in self.content_type): return self.content_type.split('charset=')[(-1)].split(';')[0].strip() return 'UTF-8'
'A dict-like SimpleCookie instance. This should not be used directly. See :meth:`set_cookie`.'
@property def COOKIES(self):
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') if (not self._cookies): self._cookies = SimpleCookie() return self._cookies
'Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below).:param key: the name of the cookie. :param value: the value of the cookie.:param secret: a signature key required for signed cookies. Additionally, this method accepts all RFC 2109 attributes that ar...
def set_cookie(self, key, value, secret=None, **options):
if (not self._cookies): self._cookies = SimpleCookie() if secret: value = touni(cookie_encode((key, value), secret)) elif (not isinstance(value, basestring)): raise TypeError('Secret key missing for non-string Cookie.') self._cookies[key] = value for (k, v) in ...
'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)