desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get/set/modify the Cache-Control header (section `14.9 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)'
def _cache_control__get(self):
env = self.environ value = env.get('HTTP_CACHE_CONTROL', '') (cache_header, cache_obj) = env.get('webob._cache_control', (None, None)) if ((cache_obj is not None) and (cache_header == value)): return cache_obj cache_obj = CacheControl.parse(value, type='request') env['webob._cache_contro...
'Call the given WSGI application, returning ``(status_string, headerlist, app_iter)`` Be sure to call ``app_iter.close()`` if it\'s there. If catch_exc_info is true, then returns ``(status_string, headerlist, app_iter, exc_info)``, where the fourth item may be None, but won\'t be if there was an exception. If you don\...
def call_application(self, application, catch_exc_info=False):
captured = [] output = [] def start_response(status, headers, exc_info=None): if ((exc_info is not None) and (not catch_exc_info)): raise exc_info[0], exc_info[1], exc_info[2] captured[:] = [status, headers, exc_info] return output.append app_iter = application(self.e...
'Like ``.call_application(application)``, except returns a response object with ``.status``, ``.headers``, and ``.body`` attributes. This will use ``self.ResponseClass`` to figure out the class of the response object to return.'
def get_response(self, application, catch_exc_info=False):
if catch_exc_info: (status, headers, app_iter, exc_info) = self.call_application(application, catch_exc_info=True) del exc_info else: (status, headers, app_iter) = self.call_application(application, catch_exc_info=False) return self.ResponseClass(status=status, headerlist=headers, ap...
'Create a blank request environ (and Request wrapper) with the given path (path should be urlencoded), and any keys from environ. The path will become path_info, with any query string split off and used. All necessary keys will be added to the environ, but the values you pass in will take precedence. If you pass in ba...
def blank(cls, path, environ=None, base_url=None, headers=None):
if _SCHEME_RE.search(path): (scheme, netloc, path, qs, fragment) = urlparse.urlsplit(path) if fragment: raise TypeError(('Path cannot contain a fragment (%r)' % fragment)) if qs: path += ('?' + qs) if (':' not in netloc): if (scheme ...
'The status string'
def _status__get(self):
return self._status
'The status as an integer'
def _status_int__get(self):
return int(self.status.split()[0])
'The list of response headers'
def _headerlist__get(self):
return self._headerlist
'Get/set the charset (in the Content-Type)'
def _charset__get(self):
header = self.headers.get('content-type') if (not header): return None match = _CHARSET_RE.search(header) if match: return match.group(1) return None
'Get/set the Content-Type header (or None), *without* the charset or any parameters. If you include parameters (or ``;`` at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved.'
def _content_type__get(self):
header = self.headers.get('content-type') if (not header): return None return header.split(';', 1)[0]
'Returns a dictionary of all the parameters in the content type.'
def _content_type_params__get(self):
params = self.headers.get('content-type', '') if (';' not in params): return {} params = params.split(';', 1)[1] result = {} for match in _PARAM_RE.finditer(params): result[match.group(1)] = (match.group(2) or match.group(3) or '') return result
'The headers in a dictionary-like object'
def _headers__get(self):
if (self._headers is None): self._headers = HeaderDict.view_list(self.headerlist) return self._headers
'The body of the response, as a ``str``. This will read in the entire app_iter if necessary.'
def _body__get(self):
if (self._body is None): if (self._app_iter is None): raise AttributeError('No body has been set') try: self._body = ''.join(self._app_iter) finally: if hasattr(self._app_iter, 'close'): self._app_iter.close() self._app_...
'Returns a file-like object that can be used to write to the body. If you passed in a list app_iter, that app_iter will be modified by writes.'
def _body_file__get(self):
return ResponseBodyFile(self)
'Get/set the unicode value of the body (using the charset of the Content-Type)'
def _unicode_body__get(self):
if (not self.charset): raise AttributeError('You cannot access Response.unicode_body unless charset is set') body = self.body return body.decode(self.charset)
'Returns the app_iter of the response. If body was set, this will create an app_iter from that body (a single-item list)'
def _app_iter__get(self):
if (self._app_iter is None): if (self._body is None): raise AttributeError('No body or app_iter has been set') return [self._body] else: return self._app_iter
'Set (add) a cookie for the response'
def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=None, httponly=False, version=None, comment=None):
cookies = BaseCookie() cookies[key] = value for (var_name, var_value) in [('max_age', max_age), ('path', path), ('domain', domain), ('secure', secure), ('HttpOnly', httponly), ('version', version), ('comment', comment)]: if ((var_value is not None) and (var_value is not False)): cookies[...
'Delete a cookie from the client. Note that path and domain must match how the cookie was originally set. This sets the cookie to the empty string, and max_age=0 so that it should expire immediately.'
def delete_cookie(self, key, path='/', domain=None):
self.set_cookie(key, '', path=path, domain=domain, max_age=0)
'Unset a cookie with the given name (remove it from the response). If there are multiple cookies (e.g., two cookies with the same name and different paths or domains), all such cookies will be deleted.'
def unset_cookie(self, key):
existing = self.headers.getall('Set-Cookie') if (not existing): raise KeyError('No cookies at all have been set') del self.headers['Set-Cookie'] found = False for header in existing: cookies = BaseCookie() cookies.load(header) if (key in cookies): ...
'Retrieve the Location header of the response, or None if there is no header. If the header is not absolute and this response is associated with a request, make the header absolute. For more information see `section 14.30 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30>`_.'
def _location__get(self):
if ('location' not in self.headers): return None location = self.headers['location'] if _SCHEME_RE.search(location): return location if (self.request is not None): base_uri = self.request.url location = urlparse.urljoin(base_uri, location) return location
'Get/set/modify the Cache-Control header (section `14.9 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)'
def _cache_control__get(self):
value = self.headers.get('cache-control', '') if (self._cache_control_obj is None): self._cache_control_obj = CacheControl.parse(value, updates_to=self._update_cache_control, type='response') self._cache_control_obj.header_value = value if (self._cache_control_obj.header_value != value): ...
'Set expiration on this request. This sets the response to expire in the given seconds, and any other attributes are used for cache_control (e.g., private=True, etc).'
def cache_expires(self, seconds=0, **kw):
cache_control = self.cache_control if isinstance(seconds, timedelta): seconds = timedelta_to_seconds(seconds) if (not seconds): cache_control.no_store = True cache_control.no_cache = True cache_control.must_revalidate = True cache_control.max_age = 0 cache_con...
'Encode the content with the given encoding (only gzip and identity are supported).'
def encode_content(self, encoding='gzip'):
if (encoding == 'identity'): return if (encoding != 'gzip'): raise ValueError(('Unknown encoding: %r' % encoding)) if self.content_encoding: if (self.content_encoding == encoding): return self.decode_content() from webob.util.safegzip import GzipFile ...
'Generate an etag for the response object using an MD5 hash of the body (the body parameter, or ``self.body`` if not given) Sets ``self.etag``'
def md5_etag(self, body=None):
if (body is None): body = self.body import md5 h = md5.new(body) self.etag = h.digest().encode('base64').replace('\n', '').strip('=')
'Return the request associated with this response if any.'
def _request__get(self):
if ((self._request is None) and (self._environ is not None)): self._request = self.RequestClass(self._environ) return self._request
'Get/set the request environ associated with this response, if any.'
def _environ__get(self):
return self._environ
'WSGI application interface'
def __call__(self, environ, start_response):
if self.conditional_response: return self.conditional_response_app(environ, start_response) start_response(self.status, self.headerlist) if (environ['REQUEST_METHOD'] == 'HEAD'): return [] return self.app_iter
'Like the normal __call__ interface, but checks conditional headers: * If-Modified-Since (304 Not Modified; only on GET, HEAD) * If-None-Match (304 Not Modified; only on GET, HEAD) * Range (406 Partial Content; only on GET, HEAD)'
def conditional_response_app(self, environ, start_response):
req = self.RequestClass(environ) status304 = False if (req.method in self._safe_methods): if (req.if_modified_since and self.last_modified and (self.last_modified <= req.if_modified_since)): status304 = True if (req.if_none_match and self.etag): if (self.etag in req.i...
'Return a new app_iter built from the response app_iter, that serves up only the given ``start:stop`` range.'
def app_iter_range(self, start, stop):
if (self._app_iter is None): return [self.body[start:stop]] app_iter = self.app_iter if hasattr(app_iter, 'app_iter_range'): return app_iter.app_iter_range(start, stop) return AppIterRange(app_iter, start, stop)
'The encoding of the file (inherited from response.charset)'
def encoding(self):
return self.response.charset
'Parse the header, returning a CacheControl object. The object is bound to the request or response object ``updates_to``, if that is given.'
def parse(cls, header, updates_to=None, type=None):
if updates_to: props = UpdateDict() props.updated = updates_to else: props = {} for match in token_re.finditer(header): name = match.group(1) value = (match.group(2) or match.group(3) or None) if value: try: value = int(value) ...
'Returns a copy of this object.'
def copy(self):
return self.__class__(self.properties.copy(), type=self.type)
'Parse this from a header value'
def parse(cls, value):
results = [] weak_results = [] while value: if value.lower().startswith('w/'): weak = True value = value[2:] else: weak = False if value.startswith('"'): try: (etag, rest) = value[1:].split('"', 1) except Val...
'Return True if the If-Range header matches the given etag or last_modified'
def match(self, etag=None, last_modified=None):
if (self.date is not None): if (last_modified is None): return False return (last_modified <= self.date) elif (self.etag is not None): if (not etag): return False return (etag in self.etag) return True
'Return True if this matches the given ``webob.Response`` instance.'
def match_response(self, response):
return self.match(etag=response.etag, last_modified=response.last_modified)
'Parse this from a header value.'
def parse(cls, value):
date = etag = None if (not value): etag = NoETag() elif (value and value.endswith(' GMT')): date = webob._parse_date(value) else: etag = ETagMatcher.parse(value) return cls(etag=etag, date=date)
'Returns true if the given object is listed in the accepted types.'
def __contains__(self, match):
for (item, quality) in self._parsed: if self._match(item, match): return True
'Return the quality of the given match. Returns None if there is no match (not 0).'
def quality(self, match):
for (item, quality) in self._parsed: if self._match(item, match): return quality return None
'Returns the first match in the sequences of matches that is allowed. Ignores quality. Returns the first item if nothing else matches; or if you include None at the end of the match list then that will be returned.'
def first_match(self, matches):
if (not matches): raise ValueError('You must pass in a non-empty list') for match in matches: for (item, quality) in self._parsed: if self._match(item, match): return match if (match is None): return None return matches[0]
'Returns the best match in the sequence of matches. The sequence can be a simple sequence, or you can have ``(match, server_quality)`` items in the sequence. If you have these tuples then the client quality is multiplied by the server_quality to get a total. default_match (default None) is returned if there is no inte...
def best_match(self, matches, default_match=None):
best_quality = (-1) best_match = default_match for match_item in matches: if isinstance(match_item, (tuple, list)): (match, server_quality) = match_item else: match = match_item server_quality = 1 for (item, quality) in self._parsed: po...
'Return all the matches in order of quality, with fallback (if given) at the end.'
def best_matches(self, fallback=None):
items = [i for (i, q) in sorted(self._parsed, key=(lambda iq: (- iq[1])))] if fallback: for (index, item) in enumerate(items): if self._match(item, fallback): items[(index + 1):] = [] break else: items.append(fallback) return items
'Returns true if any HTML-like type is accepted'
def accept_html(self):
return (('text/html' in self) or ('application/xhtml+xml' in self) or ('application/xml' in self) or ('text/xml' in self))
'Assign to new_dict.updated to track updates'
def _updated(self):
updated = self.updated if (updated is not None): args = self.updated_args if (args is None): args = (self,) updated(*args)
'Adds extra_html to the end of the html page (before </body>)'
def add_to_end(self, html, extra_html):
match = self._end_body_re.search(html) if (not match): return (html + extra_html) else: return ((html[:match.start()] + extra_html) + html[match.start():])
'Constructs a Request object from a WSGI environment. :param environ: A WSGI-compliant environment dictionary.'
def __init__(self, environ, *args, **kwargs):
if (kwargs.get('charset') is None): match = _charset_re.search(environ.get('CONTENT_TYPE', '')) if match: charset = match.group(1).lower().strip().strip('"').strip() else: charset = 'utf-8' kwargs['charset'] = charset kwargs.setdefault('unicode_errors', 'i...
'Returns the query or POST argument with the given name. We parse the query string and POST payload lazily, so this will be a slower operation on the first call. :param argument_name: The name of the query or POST argument. :param default_value: The value to return if the given argument is not present. :param allow_mul...
def get(self, argument_name, default_value='', allow_multiple=False):
param_value = self.get_all(argument_name) if allow_multiple: logging.warning('allow_multiple is a deprecated param. Please use the Request.get_all() method instead.') if (len(param_value) > 0): if allow_multiple: return param_value return par...
'Returns a list of query or POST arguments with the given name. We parse the query string and POST payload lazily, so this will be a slower operation on the first call. :param argument_name: The name of the query or POST argument. :param default_value: The value to return if the given argument is not present, None may ...
def get_all(self, argument_name, default_value=None):
if self.charset: argument_name = argument_name.encode(self.charset) if (default_value is None): default_value = [] param_value = self.params.getall(argument_name) if ((param_value is None) or (len(param_value) == 0)): return default_value for i in xrange(len(param_value)): ...
'Returns a list of the arguments provided in the query and/or POST. The return value is a list of strings.'
def arguments(self):
return list(set(self.params.keys()))
'Parses the given int argument, limiting it to the given range. :param name: The name of the argument. :param min_value: The minimum int value of the argument (if any). :param max_value: The maximum int value of the argument (if any). :param default: The default value of the argument if it is not given. :returns: An in...
def get_range(self, name, min_value=None, max_value=None, default=0):
value = self.get(name, default) if (value is None): return value try: value = int(value) except ValueError: value = default if (value is not None): if (max_value is not None): value = min(value, max_value) if (min_value is not None)...
'Adds parameters compatible with WebOb >= 1.0: POST and **kwargs.'
@classmethod def blank(cls, path, environ=None, base_url=None, headers=None, **kwargs):
try: return super(Request, cls).blank(path, environ=environ, base_url=base_url, headers=headers, **kwargs) except TypeError: if (not kwargs): raise data = kwargs.pop('POST', None) if (data is not None): from cStringIO import StringIO environ = (environ or {}) ...
'Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example:: h.add_header(...
def add_header(self, _name, _value, **_params):
parts = [] if (_value is not None): parts.append(_value) for (k, v) in _params.items(): k = k.replace('_', '-') if ((v is not None) and (len(v) > 0)): v = v.replace('\\', '\\\\').replace('"', '\\"') parts.append(('%s="%s"' % (k, v))) else: ...
'Returns the formatted headers ready for HTTP transmission.'
def __str__(self):
return '\r\n'.join(([('%s: %s' % v) for v in self.items()] + ['', '']))
'Constructs a response with the default settings.'
def __init__(self, *args, **kwargs):
super(Response, self).__init__(*args, **kwargs) self.headers['Cache-Control'] = 'no-cache'
'A reference to the Response instance itself, for compatibility with webapp only: webapp uses `Response.out.write()`, so we point `out` to `self` and it will use `Response.write()`.'
@property def out(self):
return self
'Appends a text to the response body.'
def write(self, text):
if (not isinstance(text, basestring)): text = unicode(text) if (isinstance(text, unicode) and (not self.charset)): self.charset = self.default_charset super(Response, self).write(text)
'The status string, including code and message.'
def _set_status(self, value):
message = None if isinstance(value, (int, long)): code = int(value) else: if isinstance(value, unicode): value = str(value) if (not isinstance(value, str)): raise TypeError(('You must set status to a string or integer (not %s)' % ...
'Sets the HTTP status code of this response. :param code: The HTTP status string to use :param message: A status string. If none is given, uses the default from the HTTP/1.1 specification.'
def set_status(self, code, message=None):
if message: self.status = ('%d %s' % (code, message)) else: self.status = code
'The response status message, as a string.'
def _get_status_message(self):
return self.status.split(' ', 1)[1]
'The headers as a dictionary-like object.'
def _get_headers(self):
if (self._headers is None): self._headers = ResponseHeaders.view_list(self.headerlist) return self._headers
'Indicates whether the response was an error response.'
def has_error(self):
return (self.status_int >= 400)
'Clears all data written to the output stream so that it is empty.'
def clear(self):
self.body = ''
'Writes this response using using the given WSGI function. This is only here for compatibility with ``webapp.WSGIApplication``. :param start_response: The WSGI-compatible start_response function.'
def wsgi_write(self, start_response):
if ((self.headers.get('Cache-Control') == 'no-cache') and (not self.headers.get('Expires'))): self.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT' self.headers['Content-Length'] = str(len(self.body)) write = start_response(self.status, self.headerlist) write(self.body)
'Returns the default HTTP status message for the given code. :param code: The HTTP code for which we want a message.'
@staticmethod def http_status_message(code):
message = status_reasons.get(code) if (not message): raise KeyError(('Invalid HTTP status code: %d' % code)) return message
'Initializes this request handler with the given WSGI application, Request and Response. When instantiated by ``webapp.WSGIApplication``, request and response are not set on instantiation. Instead, initialize() is called right after the handler is created to set them. Also in webapp dispatching is done by the WSGI app,...
def __init__(self, request=None, response=None):
self.initialize(request, response)
'Initializes this request handler with the given WSGI application, Request and Response. :param request: A :class:`Request` instance. :param response: A :class:`Response` instance.'
def initialize(self, request, response):
self.request = request self.response = response self.app = WSGIApplication.active_instance
'Dispatches the request. This will first check if there\'s a handler_method defined in the matched route, and if not it\'ll use the method correspondent to the request method (``get()``, ``post()`` etc).'
def dispatch(self):
request = self.request method_name = request.route.handler_method if (not method_name): method_name = _normalize_handler_method(request.method) method = getattr(self, method_name, None) if (method is None): valid = ', '.join(_get_handler_methods(self)) self.abort(405, head...
'Clears the response and sets the given HTTP status code. This doesn\'t stop code execution; for this, use :meth:`abort`. :param code: HTTP status error code (e.g., 501).'
def error(self, code):
self.response.status = code self.response.clear()
'Raises an :class:`HTTPException`. This stops code execution, leaving the HTTP exception to be handled by an exception handler. :param code: HTTP status code (e.g., 404). :param args: Positional arguments to be passed to the exception class. :param kwargs: Keyword arguments to be passed to the exception class.'
def abort(self, code, *args, **kwargs):
abort(code, *args, **kwargs)
'Issues an HTTP redirect to the given relative URI. The arguments are described in :func:`redirect`.'
def redirect(self, uri, permanent=False, abort=False, code=None, body=None):
return redirect(uri, permanent=permanent, abort=abort, code=code, body=body, request=self.request, response=self.response)
'Convenience method mixing :meth:`redirect` and :meth:`uri_for`. The arguments are described in :func:`redirect` and :func:`uri_for`.'
def redirect_to(self, _name, _permanent=False, _abort=False, _code=None, _body=None, *args, **kwargs):
uri = self.uri_for(_name, *args, **kwargs) return self.redirect(uri, permanent=_permanent, abort=_abort, code=_code, body=_body)
'Returns a URI for a named :class:`Route`. .. seealso:: :meth:`Router.build`.'
def uri_for(self, _name, *args, **kwargs):
return self.app.router.build(self.request, _name, args, kwargs)
'Called if this handler throws an exception during execution. The default behavior is to re-raise the exception to be handled by :meth:`WSGIApplication.handle_exception`. :param exception: The exception that was thrown. :param debug_mode: True if the web application is running in debug mode.'
def handle_exception(self, exception, debug):
raise
'Performs a redirect. Two keyword arguments can be passed through the URI route: - **_uri**: A URI string or a callable that returns a URI. The callable is called passing ``(handler, *args, **kwargs)`` as arguments. - **_code**: The redirect status code. Default is 301 (permanent redirect).'
def get(self, *args, **kwargs):
uri = kwargs.pop('_uri', '/') permanent = kwargs.pop('_permanent', True) code = kwargs.pop('_code', None) func = getattr(uri, '__call__', None) if func: uri = func(self, *args, **kwargs) self.redirect(uri, permanent=permanent, code=code)
'Initializes this route. :param template: A regex to be matched. :param handler: A callable or string in dotted notation to be lazily imported, e.g., ``\'my.module.MyHandler\'`` or ``\'my.module.my_function\'``. :param name: The name of this route, used to build URIs based on it. :param build_only: If True, this route ...
def __init__(self, template, handler=None, name=None, build_only=False):
if (build_only and (name is None)): raise ValueError(("Route %r is build_only but doesn't have a name." % self)) self.template = template self.handler = handler self.name = name self.build_only = build_only
'Matches all routes against a request object. The first one that matches is returned. :param request: A :class:`Request` instance. :returns: A tuple ``(route, args, kwargs)`` if a route matched, or None.'
def match(self, request):
raise NotImplementedError()
'Returns a URI for this route. :param request: The current :class:`Request` object. :param args: Tuple of positional arguments to build the URI. :param kwargs: Dictionary of keyword arguments to build the URI. :returns: An absolute or relative URI.'
def build(self, request, args, kwargs):
raise NotImplementedError()
'Generator to get all routes from a route. :yields: This route or all nested routes that it contains.'
def get_routes(self):
(yield self)
'Generator to get all routes that can be matched from a route. Match routes must implement :meth:`match`. :yields: This route or all nested routes that can be matched.'
def get_match_routes(self):
if (not self.build_only): (yield self)
'Generator to get all routes that can be built from a route. Build routes must implement :meth:`build`. :yields: A tuple ``(name, route)`` for all nested routes that can be built.'
def get_build_routes(self):
if (self.name is not None): (yield (self.name, self))
'Lazy regex compiler.'
@cached_property def regex(self):
if (not self.template.startswith('^')): self.template = ('^' + self.template) if (not self.template.endswith('$')): self.template += '$' return re.compile(self.template)
'Matches this route against the current request. .. seealso:: :meth:`BaseRoute.match`.'
def match(self, request):
match = self.regex.match(urllib.unquote(request.path)) if match: return (self, match.groups(), {})
'Initializes this route. :param template: A route template to match against the request path. A template can have variables enclosed by ``<>`` that define a name, a regular expression or both. Examples: Format Example ``<name>`` ``\'/blog/<year>/<month>\'`` ``<:regex>`` ``\'/blog/<:\d{4}>/<:\d...
def __init__(self, template, handler=None, name=None, defaults=None, build_only=False, handler_method=None, methods=None, schemes=None):
super(Route, self).__init__(template, handler=handler, name=name, build_only=build_only) self.defaults = (defaults or {}) self.methods = methods self.schemes = schemes if (isinstance(handler, basestring) and (':' in handler)): if handler_method: raise ValueError(("If handler_m...
'Lazy route template parser.'
@cached_property def regex(self):
(regex, self.reverse_template, self.args_count, self.kwargs_count, self.variables) = _parse_route_template(self.template, default_sufix='[^/]+') return regex
'Matches this route against the current request. :raises: ``exc.HTTPMethodNotAllowed`` if the route defines :attr:`methods` and the request method isn\'t allowed. .. seealso:: :meth:`BaseRoute.match`.'
def match(self, request):
match = self.regex.match(urllib.unquote(request.path)) if ((not match) or (self.schemes and (request.scheme not in self.schemes))): return None if (self.methods and (request.method not in self.methods)): raise exc.HTTPMethodNotAllowed() (args, kwargs) = _get_route_variables(match, self.d...
'Returns a URI for this route. .. seealso:: :meth:`Router.build`.'
def build(self, request, args, kwargs):
scheme = kwargs.pop('_scheme', None) netloc = kwargs.pop('_netloc', None) anchor = kwargs.pop('_fragment', None) full = (kwargs.pop('_full', False) and (not scheme) and (not netloc)) if (full or scheme or netloc): netloc = (netloc or request.host) scheme = (scheme or request.scheme) ...
'Returns the URI path for this route. :returns: A tuple ``(path, kwargs)`` with the built URI path and extra keywords to be used as URI query arguments.'
def _build(self, args, kwargs):
regex = self.regex variables = self.variables if self.args_count: for (index, value) in enumerate(args): key = ('__%d__' % index) if (key in variables): kwargs[key] = value values = {} for (name, regex) in variables.iteritems(): value = kwargs....
'Initializes the router. :param routes: A sequence of :class:`Route` instances or, for simple routes, tuples ``(regex, handler)``.'
def __init__(self, routes=None):
self.match_routes = [] self.build_routes = {} self.handlers = {} if routes: for route in routes: self.add(route)
'Adds a route to this router. :param route: A :class:`Route` instance or, for simple routes, a tuple ``(regex, handler)``.'
def add(self, route):
if isinstance(route, tuple): route = self.route_class(*route) for r in route.get_match_routes(): self.match_routes.append(r) for (name, r) in route.get_build_routes(): self.build_routes[name] = r
'Sets the function called to match URIs. :param func: A function that receives ``(router, request)`` and returns a tuple ``(route, args, kwargs)`` if any route matches, or raise ``exc.HTTPNotFound`` if no route matched or ``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP method was not allowed.'
def set_matcher(self, func):
self.match = func.__get__(self, self.__class__)
'Sets the function called to build URIs. :param func: A function that receives ``(router, request, name, args, kwargs)`` and returns a URI.'
def set_builder(self, func):
self.build = func.__get__(self, self.__class__)
'Sets the function called to dispatch the handler. :param func: A function that receives ``(router, request, response)`` and returns the value returned by the dispatched handler.'
def set_dispatcher(self, func):
self.dispatch = func.__get__(self, self.__class__)
'Sets the function that adapts loaded handlers for dispatching. :param func: A function that receives ``(router, handler)`` and returns a handler callable.'
def set_adapter(self, func):
self.adapt = func.__get__(self, self.__class__)
'Matches all routes against a request object. The first one that matches is returned. :param request: A :class:`Request` instance. :returns: A tuple ``(route, args, kwargs)`` if a route matched, or None. :raises: ``exc.HTTPNotFound`` if no route matched or ``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP me...
def default_matcher(self, request):
method_not_allowed = False for route in self.match_routes: try: match = route.match(request) if match: return match except exc.HTTPMethodNotAllowed: method_not_allowed = True if method_not_allowed: raise exc.HTTPMethodNotAllowed() ...
'Returns a URI for a named :class:`Route`. :param request: The current :class:`Request` object. :param name: The route name. :param args: Tuple of positional arguments to build the URI. All positional variables defined in the route must be passed and must conform to the format set in the route. Extra arguments are igno...
def default_builder(self, request, name, args, kwargs):
route = self.build_routes.get(name) if (route is None): raise KeyError(('Route named %r is not defined.' % name)) return route.build(request, args, kwargs)
'Dispatches a handler. :param request: A :class:`Request` instance. :param response: A :class:`Response` instance. :raises: ``exc.HTTPNotFound`` if no route matched or ``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP method was not allowed. :returns: The returned value from the handler.'
def default_dispatcher(self, request, response):
(route, args, kwargs) = rv = self.match(request) (request.route, request.route_args, request.route_kwargs) = rv if (route.handler_adapter is None): handler = route.handler if isinstance(handler, basestring): if (handler not in self.handlers): self.handlers[handler...
'Adapts a handler for dispatching. Because handlers use or implement different dispatching mechanisms, they can be wrapped to use a unified API for dispatching. This way webapp2 can support, for example, a :class:`RequestHandler` class and function views or, for compatibility purposes, a ``webapp.RequestHandler`` class...
def default_adapter(self, handler):
if inspect.isclass(handler): if (_webapp and issubclass(handler, _webapp.RequestHandler)): adapter = WebappHandlerAdapter else: adapter = Webapp2HandlerAdapter else: adapter = BaseHandlerAdapter return adapter(handler)
'Returns a configuration for a given key. This can be used by objects that define a default configuration. It will update the app configuration with the default values the first time it is requested, and mark the key as loaded. :param key: A configuration key. :param default_values: Default values defined by a module o...
def load_config(self, key, default_values=None, user_values=None, required_keys=None):
if (key in self.loaded): config = self[key] else: config = dict((default_values or ())) if (key in self): config.update(self[key]) self[key] = config self.loaded.append(key) if (required_keys and (not user_values)): self._validate_required(...
'Initializes the request context. :param app: An :class:`WSGIApplication` instance. :param environ: A WSGI environment dictionary.'
def __init__(self, app, environ):
self.app = app self.environ = environ
'Enters the request context. :returns: A tuple ``(request, response)``.'
def __enter__(self):
request = self.app.request_class(self.environ) response = self.app.response_class() request.app = self.app request.response = response self.app.set_globals(app=self.app, request=request) return (request, response)
'Exits the request context. This release the context locals except if an exception is caught in debug mode. In this case they are kept to be inspected.'
def __exit__(self, exc_type, exc_value, traceback):
if ((exc_type is None) or (not self.app.debug)): self.app.clear_globals()
'Initializes the WSGI application. :param routes: A sequence of :class:`Route` instances or, for simple routes, tuples ``(regex, handler)``. :param debug: True to enable debug mode, False otherwise. :param config: A configuration dictionary for the application.'
def __init__(self, routes=None, debug=False, config=None):
self.debug = debug self.registry = {} self.error_handlers = {} self.set_globals(app=self) self.config = self.config_class(config) self.router = self.router_class(routes)