desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Month, textual, 3 letters, lowercase; e.g. \'jan\''
| def b(self):
| return MONTHS_3[self.data.month]
|
'ISO 8601 Format
Example : \'2008-01-02T10:30:00.000123\''
| def c(self):
| return self.data.isoformat()
|
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
| def d(self):
| return (u'%02d' % self.data.day)
|
'Day of the week, textual, 3 letters; e.g. \'Fri\''
| def D(self):
| return WEEKDAYS_ABBR[self.data.weekday()]
|
'Alternative month names as required by some locales. Proprietary extension.'
| def E(self):
| return MONTHS_ALT[self.data.month]
|
'Month, textual, long; e.g. \'January\''
| def F(self):
| return MONTHS[self.data.month]
|
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
| def I(self):
| if (self.timezone and self.timezone.dst(self.data)):
return u'1'
else:
return u'0'
|
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
| def j(self):
| return self.data.day
|
'Day of the week, textual, long; e.g. \'Friday\''
| def l(self):
| return WEEKDAYS[self.data.weekday()]
|
'Boolean for whether it is a leap year; i.e. True or False'
| def L(self):
| return calendar.isleap(self.data.year)
|
'Month; i.e. \'01\' to \'12\''
| def m(self):
| return (u'%02d' % self.data.month)
|
'Month, textual, 3 letters; e.g. \'Jan\''
| def M(self):
| return MONTHS_3[self.data.month].title()
|
'Month without leading zeros; i.e. \'1\' to \'12\''
| def n(self):
| return self.data.month
|
'Month abbreviation in Associated Press style. Proprietary extension.'
| def N(self):
| return MONTHS_AP[self.data.month]
|
'Difference to Greenwich time in hours; e.g. \'+0200\''
| def O(self):
| seconds = self.Z()
return (u'%+03d%02d' % ((seconds // 3600), ((seconds // 60) % 60)))
|
'RFC 2822 formatted date; e.g. \'Thu, 21 Dec 2000 16:01:07 +0200\''
| def r(self):
| return self.format('D, j M Y H:i:s O')
|
'English ordinal suffix for the day of the month, 2 characters; i.e. \'st\', \'nd\', \'rd\' or \'th\''
| def S(self):
| if (self.data.day in (11, 12, 13)):
return u'th'
last = (self.data.day % 10)
if (last == 1):
return u'st'
if (last == 2):
return u'nd'
if (last == 3):
return u'rd'
return u'th'
|
'Number of days in the given month; i.e. \'28\' to \'31\''
| def t(self):
| return (u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1])
|
'Time zone of this machine; e.g. \'EST\' or \'MDT\''
| def T(self):
| name = ((self.timezone and self.timezone.tzname(self.data)) or None)
if (name is None):
name = self.format('O')
return unicode(name)
|
'Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)'
| def U(self):
| if getattr(self.data, 'tzinfo', None):
return int(calendar.timegm(self.data.utctimetuple()))
else:
return int(time.mktime(self.data.timetuple()))
|
'Day of the week, numeric, i.e. \'0\' (Sunday) to \'6\' (Saturday)'
| def w(self):
| return ((self.data.weekday() + 1) % 7)
|
'ISO-8601 week number of year, weeks starting on Monday'
| def W(self):
| week_number = None
jan1_weekday = (self.data.replace(month=1, day=1).weekday() + 1)
weekday = (self.data.weekday() + 1)
day_of_year = self.z()
if ((day_of_year <= (8 - jan1_weekday)) and (jan1_weekday > 4)):
if ((jan1_weekday == 5) or ((jan1_weekday == 6) and calendar.isleap((self.data.year ... |
'Year, 2 digits; e.g. \'99\''
| def y(self):
| return unicode(self.data.year)[2:]
|
'Year, 4 digits; e.g. \'1999\''
| def Y(self):
| return self.data.year
|
'Day of the year; i.e. \'0\' to \'365\''
| def z(self):
| doy = (self.year_days[self.data.month] + self.data.day)
if (self.L() and (self.data.month > 2)):
doy += 1
return doy
|
'Time zone offset in seconds (i.e. \'-43200\' to \'43200\'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.'
| def Z(self):
| if (not self.timezone):
return 0
offset = self.timezone.utcoffset(self.data)
return ((offset.days * 86400) + offset.seconds)
|
'Get information about any POST forms in the template.
Returns [(linenumber, csrf_token added)]'
| def post_form_info(self):
| forms = {}
form_line = 0
for (ln, line) in enumerate(self.content.split('\n')):
if ((not form_line) and _POST_FORM_RE.search(line)):
form_line = (ln + 1)
forms[form_line] = False
if (form_line and _TOKEN_RE.search(line)):
forms[form_line] = True
... |
'Returns true if this template includes template \'t\' (via {% include %})'
| def includes_template(self, t):
| for r in t.relative_filenames:
if re.search((('\\{%\\s*include\\s+(\\\'|")' + re.escape(r)) + '(\\1)\\s*%\\}'), self.content):
return True
return False
|
'Returns all templates that include this one, recursively. (starting
with this one)'
| def related_templates(self):
| try:
return self._related_templates
except AttributeError:
pass
retval = set([self])
for t in self.all_templates:
if t.includes_template(self):
retval = retval.union(t.related_templates())
self._related_templates = retval
return retval
|
'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) and (not hasattr(webob, '__version__'))):
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
... |
'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)
|
'Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don\'t support threading.
If :mod:`web... | def set_globals(self, app=None, request=None):
| if (_local is not None):
_local.app = app
_local.request = request
else:
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
|
'Clears global variables. See :meth:`set_globals`.'
| def clear_globals(self):
| if (_local is not None):
_local.__release_local__()
else:
WSGIApplication.app = WSGIApplication.active_instance = None
WSGIApplication.request = None
|
'Called by WSGI when a request comes in.
:param environ:
A WSGI environment.
:param start_response:
A callable accepting a status code, a list of headers and an
optional exception context to start the response.
:returns:
An iterable with the response to return to the client.'
| def __call__(self, environ, start_response):
| with self.request_context_class(self, environ) as (request, response):
try:
if (request.method not in self.allowed_methods):
raise exc.HTTPNotImplemented()
rv = self.router.dispatch(request, response)
if (rv is not None):
response = rv
... |
'Last resource error for :meth:`__call__`.'
| def _internal_error(self, exception):
| logging.exception(exception)
if self.debug:
lines = ''.join(traceback.format_exception(*sys.exc_info()))
html = (_debug_template % cgi.escape(lines, quote=True))
return Response(body=html, status=500)
return exc.HTTPInternalServerError()
|
'Handles a uncaught exception occurred in :meth:`__call__`.
Uncaught exceptions can be handled by error handlers registered in
:attr:`error_handlers`. This is a dictionary that maps HTTP status
codes to callables that will handle the corresponding error code.
If the exception is not an ``HTTPException``, the status cod... | def handle_exception(self, request, response, e):
| if isinstance(e, HTTPException):
code = e.code
else:
code = 500
handler = self.error_handlers.get(code)
if handler:
if isinstance(handler, basestring):
self.error_handlers[code] = handler = import_string(handler)
return handler(request, response, e)
else:
... |
'Runs this WSGI-compliant application in a CGI environment.
This uses functions provided by ``google.appengine.ext.webapp.util``,
if available: ``run_bare_wsgi_app`` and ``run_wsgi_app``.
Otherwise, it uses ``wsgiref.handlers.CGIHandler().run()``.
:param bare:
If True, doesn\'t add registered WSGI middleware: use
``run... | def run(self, bare=False):
| if _webapp_util:
if bare:
_webapp_util.run_bare_wsgi_app(self)
else:
_webapp_util.run_wsgi_app(self)
else:
handlers.CGIHandler().run(self)
|
'Creates a request and returns a response for this app.
This is a convenience for unit testing purposes. It receives
parameters to build a request and calls the application, returning
the resulting response::
class HelloHandler(webapp2.RequestHandler):
def get(self):
self.response.write(\'Hello, world!\')
app = webapp2... | def get_response(self, *args, **kwargs):
| return self.request_class.blank(*args, **kwargs).get_response(self)
|
'Creates a proxy for a name.'
| def __call__(self, proxy):
| return LocalProxy(self, proxy)
|
'Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.'
| def _get_current_object(self):
| if (not hasattr(self.__local, '__release_local__')):
return self.__local()
try:
return getattr(self.__local, self.__name__)
except AttributeError:
raise RuntimeError(('no object bound to %s' % self.__name__))
|
'Renders a template and returns a response object.
:param _filename:
The template filename, related to the templates directory.
:param context:
Keyword arguments used as variables in the rendered template.
These will override values set in the request context.
:returns:
A rendered template.'
| def render_template(self, _filename, **context):
| template = self.environment.get_template(_filename)
return template.render_unicode(**context)
|
'Initializes the configuration object.
:param values:
A dictionary of configuration dictionaries for modules.
:param defaults:
A dictionary of configuration dictionaries for initial default
values. These modules are marked as loaded.'
| def __init__(self, values=None, defaults=None):
| self.loaded = []
if (values is not None):
assert isinstance(values, dict)
for (module, config) in values.iteritems():
self.update(module, config)
if (defaults is not None):
assert isinstance(defaults, dict)
for (module, config) in defaults.iteritems():
... |
'Returns the configuration for a module. If it is not already
set, loads a ``default_config`` variable from the given module and
updates the configuration with those default values
Every module that allows some kind of configuration sets a
``default_config`` global variable that is loaded by this function,
cached and u... | def __getitem__(self, module):
| if (module not in self.loaded):
values = webapp2.import_string((module + '.default_config'), silent=True)
if values:
self.setdefault(module, values)
self.loaded.append(module)
try:
return dict.__getitem__(self, module)
except KeyError:
raise KeyError(('Mod... |
'Sets a configuration for a module, requiring it to be a dictionary.
:param module:
A module name for the configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.'
| def __setitem__(self, module, values):
| assert isinstance(values, dict), 'Module configuration must be a dict.'
dict.__setitem__(self, module, SubConfig(module, values))
|
'Returns a configuration for a module. If default is not provided,
returns an empty dict if the module is not configured.
:param module:
The module name.
:params default:
Default value to return if the module is not configured. If not
set, returns an empty dict.
:returns:
A module configuration.'
| def get(self, module, default=DEFAULT_VALUE):
| if (default is DEFAULT_VALUE):
default = {}
return dict.get(self, module, default)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.