desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
cred: The OAuth2Credential to update/set
scope: The scope(s) that this credential covers'
| def _update_credential(self, cred, scope):
| key = (cred.client_id, cred.user_agent, scope)
self._data[key] = cred
self._write()
|
'Get a Storage object to get/set a credential.
This Storage is a \'view\' into the multistore.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
A Storage object that can be used to get/set this cred'
| def _get_storage(self, client_id, user_agent, scope):
| return self._Storage(self, client_id, user_agent, scope)
|
'Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can\'t detect
if an error occurred.'
| def do_GET(s):
| s.send_response(200)
s.send_header('Content-type', 'text/html')
s.end_headers()
query = s.path.split('?', 1)[(-1)]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write('<html><head><title>Authentication Status</title></head>')
s.wfile.write('<body><p>The authe... |
'Do not log messages to stdout while running as command line program.'
| def log_message(self, format, *args):
| pass
|
'Constructor.
Args:
pubkey, OpenSSL.crypto.PKey, The public key to verify with.'
| def __init__(self, pubkey):
| self._pubkey = pubkey
|
'Verifies a message against a signature.
Args:
message: string, The message to verify.
signature: string, The signature on the message.
Returns:
True if message was singed by the private key associated with the public
key that this object was constructed with.'
| def verify(self, message, signature):
| try:
crypto.verify(self._pubkey, signature, message, 'sha256')
return True
except:
return False
|
'Construct a Verified instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
expected to be an RSA key in PEM format.
Returns:
Verifier instance.
Raises:
OpenSSL.crypto.Error if the key_pem can\'t be parsed.'
| @staticmethod
def from_string(key_pem, is_x509_cert):
| if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else:
pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
return Verifier(pubkey)
|
'Constructor.
Args:
pkey, OpenSSL.crypto.PKey, The private key to sign with.'
| def __init__(self, pkey):
| self._key = pkey
|
'Signs a message.
Args:
message: string, Message to be signed.
Returns:
string, The signature of the message for the given key.'
| def sign(self, message):
| return crypto.sign(self._key, message, 'sha256')
|
'Construct a Signer instance from a string.
Args:
key: string, private key in P12 format.
password: string, password for the private key file.
Returns:
Signer instance.
Raises:
OpenSSL.crypto.Error if the key can\'t be parsed.'
| @staticmethod
def from_string(key, password='notasecret'):
| pkey = crypto.load_pkcs12(key, password).get_privatekey()
return Signer(pkey)
|
'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):
va... |
'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.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)
|
'Sets a default configuration dictionary for a module.
:param module:
The module to set default configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.
:returns:
The module configuration dictionary.'
| def setdefault(self, module, values):
| assert isinstance(values, dict), 'Module configuration must be a dict.'
if (module not in self):
dict.__setitem__(self, module, SubConfig(module))
module_dict = dict.__getitem__(self, module)
for (key, value) in values.iteritems():
module_dict.setdefault(key, value)
re... |
'Updates the configuration dictionary for a module.
:param module:
The module to update the configuration, e.g.: `webapp2.ext.i18n`.
:param values:
A dictionary of configurations for the module.'
| def update(self, module, values):
| assert isinstance(values, dict), 'Module configuration must be a dict.'
if (module not in self):
dict.__setitem__(self, module, SubConfig(module))
dict.__getitem__(self, module).update(values)
|
'Returns a configuration value for a module and optionally a key.
Will raise a KeyError if they the module is not configured or the key
doesn\'t exist and a default is not provided.
:param module:
The module name.
:params key:
The configuration key.
:param default:
Default value to return if the key doesn\'t exist.
:re... | def get_config(self, module, key=None, default=REQUIRED_VALUE):
| module_dict = self.__getitem__(module)
if (key is None):
return module_dict
return module_dict.get(key, default)
|
'Initializes the i18n store.
:param app:
A :class:`webapp2.WSGIApplication` instance.
:param config:
A dictionary of configuration values to be overridden. See
the available keys in :data:`default_config`.'
| def __init__(self, app, config=None):
| config = app.config.load_config(self.config_key, default_values=default_config, user_values=config, required_keys=None)
self.translations = {}
self.translations_path = config['translations_path']
self.domains = config['domains']
self.default_locale = config['default_locale']
self.default_timezon... |
'Sets the function that defines the locale for a request.
:param func:
A callable that receives (store, request) and returns the locale
for a request.'
| def set_locale_selector(self, func):
| if (func is None):
self.locale_selector = self.default_locale_selector
else:
if isinstance(func, basestring):
func = webapp2.import_string(func)
self.locale_selector = func.__get__(self, self.__class__)
|
'Sets the function that defines the timezone for a request.
:param func:
A callable that receives (store, request) and returns the timezone
for a request.'
| def set_timezone_selector(self, func):
| if (func is None):
self.timezone_selector = self.default_timezone_selector
else:
if isinstance(func, basestring):
func = webapp2.import_string(func)
self.timezone_selector = func.__get__(self, self.__class__)
|
'Returns a translation catalog for a locale.
:param locale:
A locale code.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.'
| def get_translations(self, locale):
| trans = self.translations.get(locale)
if (not trans):
locales = (locale, self.default_locale)
trans = self.load_translations(self.translations_path, locales, self.domains)
if (not webapp2.get_app().debug):
self.translations[locale] = trans
return trans
|
'Loads a translation catalog.
:param dirname:
Path to where translations are stored.
:param locales:
A list of locale codes.
:param domains:
A list of domains to be merged.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.'
| def load_translations(self, dirname, locales, domains):
| trans = None
trans_null = None
for domain in domains:
_trans = support.Translations.load(dirname, locales, domain)
if isinstance(_trans, NullTranslations):
trans_null = _trans
continue
elif (trans is None):
trans = _trans
else:
... |
'Initializes the i18n provider for a request.
:param request:
A :class:`webapp2.Request` instance.'
| def __init__(self, request):
| self.store = store = get_store(app=request.app)
self.set_locale(store.locale_selector(request))
self.set_timezone(store.timezone_selector(request))
|
'Sets the locale code for this request.
:param locale:
A locale code.'
| def set_locale(self, locale):
| self.locale = locale
self.translations = self.store.get_translations(locale)
|
'Sets the timezone code for this request.
:param timezone:
A timezone code.'
| def set_timezone(self, timezone):
| self.timezone = timezone
self.tzinfo = pytz.timezone(timezone)
|
'Translates a given string according to the current locale.
:param string:
The string to be translated.
:param variables:
Variables to format the returned string.
:returns:
The translated string.'
| def gettext(self, string, **variables):
| if variables:
return (self.translations.ugettext(string) % variables)
return self.translations.ugettext(string)
|
'Translates a possible pluralized string according to the current
locale.
:param singular:
The singular for of the string to be translated.
:param plural:
The plural for of the string to be translated.
:param n:
An integer indicating if this is a singular or plural. If greater
than 1, it is a plural.
:param variables:
... | def ngettext(self, singular, plural, n, **variables):
| if variables:
return (self.translations.ungettext(singular, plural, n) % variables)
return self.translations.ungettext(singular, plural, n)
|
'Returns a datetime object converted to the local timezone.
:param datetime:
A ``datetime`` object.
:returns:
A ``datetime`` object normalized to a timezone.'
| def to_local_timezone(self, datetime):
| if (datetime.tzinfo is None):
datetime = datetime.replace(tzinfo=pytz.UTC)
return self.tzinfo.normalize(datetime.astimezone(self.tzinfo))
|
'Returns a datetime object converted to UTC and without tzinfo.
:param datetime:
A ``datetime`` object.
:returns:
A naive ``datetime`` object (no timezone), converted to UTC.'
| def to_utc(self, datetime):
| if (datetime.tzinfo is None):
datetime = self.tzinfo.localize(datetime)
return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
|
'A helper for the datetime formatting functions. Returns a format
name or pattern to be used by Babel date format functions.
:param key:
A format key to be get from config. Valid values are "date",
"datetime" or "time".
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a cu... | def _get_format(self, key, format):
| if (format is None):
format = self.store.date_formats.get(key)
if (format in ('short', 'medium', 'full', 'long', 'iso')):
rv = self.store.date_formats.get(('%s.%s' % (key, format)))
if (rv is not None):
format = rv
return format
|
'Returns a date formatted according to the given pattern and
following the current locale.
:param date:
A ``date`` or ``datetime`` object. If None, the current date in
UTC is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern. Example outputs... | def format_date(self, date=None, format=None, rebase=True):
| format = self._get_format('date', format)
if (rebase and isinstance(date, datetime.datetime)):
date = self.to_local_timezone(date)
return dates.format_date(date, format, locale=self.locale)
|
'Returns a date and time formatted according to the given pattern
and following the current locale and timezone.
:param datetime:
A ``datetime`` object. If None, the current date and time in UTC
is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time p... | def format_datetime(self, datetime=None, format=None, rebase=True):
| format = self._get_format('datetime', format)
kwargs = {}
if rebase:
kwargs['tzinfo'] = self.tzinfo
return dates.format_datetime(datetime, format, locale=self.locale, **kwargs)
|
'Returns a time formatted according to the given pattern and
following the current locale and timezone.
:param time:
A ``time`` or ``datetime`` object. If None, the current
time in UTC is used.
:param format:
The format to be returned. Valid values are "short", "medium",
"long", "full" or a custom date/time pattern. Ex... | def format_time(self, time=None, format=None, rebase=True):
| format = self._get_format('time', format)
kwargs = {}
if rebase:
kwargs['tzinfo'] = self.tzinfo
return dates.format_time(time, format, locale=self.locale, **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.