desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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: raise 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)
'Construct a new service handler instance.'
def __call__(self, request, *args, **kwargs):
handler = ServiceHandler(request, request.response) handler.dispatch(self, self.service_factory())
'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)
'Formats the elapsed time from the given date to now or the given timedelta. This currently requires an unreleased development version of Babel. :param datetime_or_timedelta: A ``timedelta`` object representing the time difference to format, or a ``datetime`` object in UTC. :param granularity: Determines the smallest u...
def format_timedelta(self, datetime_or_timedelta, granularity='second', threshold=0.85):
if isinstance(datetime_or_timedelta, datetime.datetime): datetime_or_timedelta = (datetime.datetime.utcnow() - datetime_or_timedelta) return dates.format_timedelta(datetime_or_timedelta, granularity, threshold=threshold, locale=self.locale)
'Returns the given number formatted for the current locale. Example:: >>> format_number(1099, locale=\'en_US\') u\'1,099\' :param number: The number to format. :returns: The formatted number.'
def format_number(self, number):
return numbers.format_number(number, locale=self.locale)
'Returns the given decimal number formatted for the current locale. Example:: >>> format_decimal(1.2345, locale=\'en_US\') u\'1.234\' >>> format_decimal(1.2346, locale=\'en_US\') u\'1.235\' >>> format_decimal(-1.2346, locale=\'en_US\') u\'-1.235\' >>> format_decimal(1.2345, locale=\'sv_SE\') u\'1,234\' >>> format_decim...
def format_decimal(self, number, format=None):
return numbers.format_decimal(number, format=format, locale=self.locale)
'Returns a formatted currency value. Example:: >>> format_currency(1099.98, \'USD\', locale=\'en_US\') u\'$1,099.98\' >>> format_currency(1099.98, \'USD\', locale=\'es_CO\') u\'US$\xa01.099,98\' >>> format_currency(1099.98, \'EUR\', locale=\'de_DE\') u\'1.099,98\xa0\u20ac\' The pattern can also be specified explicitly:...
def format_currency(self, number, currency, format=None):
return numbers.format_currency(number, currency, format=format, locale=self.locale)
'Returns formatted percent value for the current locale. Example:: >>> format_percent(0.34, locale=\'en_US\') u\'34%\' >>> format_percent(25.1234, locale=\'en_US\') u\'2,512%\' >>> format_percent(25.1234, locale=\'sv_SE\') u\'2\xa0512\xa0%\' The format pattern can also be specified explicitly:: >>> format_percent(25.12...
def format_percent(self, number, format=None):
return numbers.format_percent(number, format=format, locale=self.locale)
'Returns value formatted in scientific notation for the current locale. Example:: >>> format_scientific(10000, locale=\'en_US\') u\'1E4\' The format pattern can also be specified explicitly:: >>> format_scientific(1234567, u\'##0E00\', locale=\'en_US\') u\'1.23E06\' :param number: The number to format. :param format: N...
def format_scientific(self, number, format=None):
return numbers.format_scientific(number, format=format, locale=self.locale)
'Parses a date from a string. This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. Example:: >>> parse_date(\'4/1/04\', locale=\'en_US\') datetime.date(2004, 4, 1) >>> parse_date(\'01.04.2004\', locale=\'de_DE\') datetime.date(2004, 4, 1) :par...
def parse_date(self, string):
return dates.parse_date(string, locale=self.locale)
'Parses a date and time from a string. This function uses the date and time formats for the locale as a hint to determine the order in which the time fields appear in the string. :param string: The string containing the date and time. :returns: The parsed datetime object.'
def parse_datetime(self, string):
return dates.parse_datetime(string, locale=self.locale)
'Parses a time from a string. This function uses the time format for the locale as a hint to determine the order in which the time fields appear in the string. Example:: >>> parse_time(\'15:30:00\', locale=\'en_US\') datetime.time(15, 30) :param string: The string containing the time. :returns: The parsed time object.'...
def parse_time(self, string):
return dates.parse_time(string, locale=self.locale)
'Parses localized number string into a long integer. Example:: >>> parse_number(\'1,099\', locale=\'en_US\') 1099L >>> parse_number(\'1.099\', locale=\'de_DE\') 1099L When the given string cannot be parsed, an exception is raised:: >>> parse_number(\'1.099,98\', locale=\'de\') Traceback (most recent call last): NumberF...
def parse_number(self, string):
return numbers.parse_number(string, locale=self.locale)
'Parses localized decimal string into a float. Example:: >>> parse_decimal(\'1,099.98\', locale=\'en_US\') 1099.98 >>> parse_decimal(\'1.099,98\', locale=\'de\') 1099.98 When the given string cannot be parsed, an exception is raised:: >>> parse_decimal(\'2,109,998\', locale=\'de\') Traceback (most recent call last): Nu...
def parse_decimal(self, string):
return numbers.parse_decimal(string, locale=self.locale)
'Returns a representation of the given timezone using "location format". The result depends on both the local display name of the country and the city assocaited with the time zone:: >>> from pytz import timezone >>> tz = timezone(\'America/St_Johns\') >>> get_timezone_location(tz, locale=\'de_DE\') u"Kanada (St. John\...
def get_timezone_location(self, dt_or_tzinfo):
return dates.get_timezone_name(dt_or_tzinfo, locale=self.locale)
'Initiliazes the serializer/deserializer. :param secret_key: A random string to be used as the HMAC secret for the cookie signature.'
def __init__(self, secret_key):
self.secret_key = secret_key
'Serializes a signed cookie value. :param name: Cookie name. :param value: Cookie value to be serialized. :returns: A serialized value ready to be stored in a cookie.'
def serialize(self, name, value):
timestamp = str(self._get_timestamp()) value = self._encode(value) signature = self._get_signature(name, value, timestamp) return '|'.join([value, timestamp, signature])
'Deserializes a signed cookie value. :param name: Cookie name. :param value: A cookie value to be deserialized. :param max_age: Maximum age in seconds for a valid cookie. If the cookie is older than this, returns None. :returns: The deserialized secure cookie, or None if it is not valid.'
def deserialize(self, name, value, max_age=None):
if (not value): return None parts = value.split('|') if (len(parts) != 3): return None signature = self._get_signature(name, parts[0], parts[1]) if (not security.compare_hashes(parts[2], signature)): logging.warning('Invalid cookie signature %r', value) retur...
'Generates an HMAC signature.'
def _get_signature(self, *parts):
signature = hmac.new(self.secret_key, digestmod=hashlib.sha1) signature.update('|'.join(parts)) return signature.hexdigest()
'Initializes the session 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):
self.app = app self.config = app.config.load_config(self.config_key, default_values=default_config, user_values=config)
'The list of attributes stored in a session. This must be an ordered list of unique elements.'
@webapp2.cached_property def session_attributes(self):
seen = set() attrs = (self._session_attributes + self.user_attributes) return [a for a in attrs if ((a not in seen) and (not seen.add(a)))]
'The list of attributes retrieved from the user model. This must be an ordered list of unique elements.'
@webapp2.cached_property def user_attributes(self):
seen = set() attrs = self.config['user_attributes'] return [a for a in attrs if ((a not in seen) and (not seen.add(a)))]
'Configured user model.'
@webapp2.cached_property def user_model(self):
cls = self.config['user_model'] if isinstance(cls, basestring): cls = self.config['user_model'] = webapp2.import_string(cls) return cls
'Returns a user dict based on auth_id and password. :param auth_id: Authentication id. :param password: User password. :param silent: If True, raises an exception if auth_id or password are invalid. :returns: A dictionary with user data. :raises: ``InvalidAuthIdError`` or ``InvalidPasswordError``.'
def get_user_by_auth_password(self, auth_id, password, silent=False):
try: user = self.user_model.get_by_auth_password(auth_id, password) return self.user_to_dict(user) except (InvalidAuthIdError, InvalidPasswordError): if (not silent): raise return None
'Returns a user dict based on user_id and auth token. :param user_id: User id. :param token: Authentication token. :returns: A tuple ``(user_dict, token_timestamp)``. Both values can be None. The token timestamp will be None if the user is invalid or it is valid but the token requires renewal.'
def get_user_by_auth_token(self, user_id, token):
(user, ts) = self.user_model.get_by_auth_token(user_id, token) return (self.user_to_dict(user), ts)
'Creates a new authentication token. :param user_id: Authentication id. :returns: A new authentication token.'
def create_auth_token(self, user_id):
return self.user_model.create_auth_token(user_id)
'Deletes an authentication token. :param user_id: User id. :param token: Authentication token.'
def delete_auth_token(self, user_id, token):
return self.user_model.delete_auth_token(user_id, token)
'Returns a dictionary based on a user object. Extra attributes to be retrieved must be set in this module\'s configuration. :param user: User object: an instance the custom user model. :returns: A dictionary with user data.'
def user_to_dict(self, user):
if (not user): return None user_dict = dict(((a, getattr(user, a)) for a in self.user_attributes)) user_dict['user_id'] = user.get_id() return user_dict
'Returns an auth session. :param request: A :class:`webapp2.Request` instance. :returns: A session dict.'
def get_session(self, request):
store = sessions.get_store(request=request) return store.get_session(self.config['cookie_name'], backend=self.config['session_backend'])
'Serializes values for a session. :param data: A dict with session data. :returns: A list with session data.'
def serialize_session(self, data):
try: assert (len(data) >= len(self.session_attributes)) return [data.get(k) for k in self.session_attributes] except AssertionError: logging.warning(('Invalid user data: %r. Expected attributes: %r.' % (data, self.session_attributes))) return None
'Deserializes values for a session. :param data: A list with session data. :returns: A dict with session data.'
def deserialize_session(self, data):
try: assert (len(data) >= len(self.session_attributes)) return dict(zip(self.session_attributes, data)) except AssertionError: logging.warning(('Invalid user data: %r. Expected attributes: %r.' % (data, self.session_attributes))) return None
'Validates a password. Passwords are used to log-in using forms or to request auth tokens from services. :param auth_id: Authentication id. :param password: Password to be checked. :param silent: If True, raises an exception if auth_id or password are invalid. :returns: user or None :raises: ``InvalidAuthIdError`` or `...
def validate_password(self, auth_id, password, silent=False):
return self.get_user_by_auth_password(auth_id, password, silent=silent)
'Validates a token. Tokens are random strings used to authenticate temporarily. They are used to validate sessions or service requests. :param user_id: User id. :param token: Token to be checked. :param token_ts: Optional token timestamp used to pre-validate the token age. :returns: A tuple ``(user_dict, token)``.'
def validate_token(self, user_id, token, token_ts=None):
now = int(time.time()) delete = (token_ts and ((now - token_ts) > self.config['token_max_age'])) create = False if (not delete): (user, ts) = self.get_user_by_auth_token(user_id, token) if user: delete = ((now - ts) > self.config['token_max_age']) create = ((now -...
'Validates a cache timestamp. :param cache_ts: Token timestamp to validate the cache age. :param token_ts: Token timestamp to validate the token age. :returns: True if it is valid, False otherwise.'
def validate_cache_timestamp(self, cache_ts, token_ts=None):
now = int(time.time()) valid = ((now - cache_ts) < self.config['token_cache_age']) if (valid and token_ts): valid2 = ((now - token_ts) < self.config['token_max_age']) valid3 = ((now - token_ts) < self.config['token_new_age']) valid = (valid2 and valid3) return valid
'Initializes the auth provider for a request. :param request: A :class:`webapp2.Request` instance.'
def __init__(self, request):
self.request = request self.store = get_store(app=request.app)
'Returns a user based on the current session. :param save_session: If True, saves the user in the session if authentication succeeds. :returns: A user dict or None.'
def get_user_by_session(self, save_session=True):
if (self._user is None): data = self.get_session_data(pop=True) if (not data): self._user = _anon else: self._user = self.get_user_by_token(user_id=data['user_id'], token=data['token'], token_ts=data['token_ts'], cache=data, cache_ts=data['cache_ts'], remember=data['r...
'Returns a user based on an authentication token. :param user_id: User id. :param token: Authentication token. :param token_ts: Token timestamp, used to perform pre-validation. :param cache: Cached user data (from the session). :param cache_ts: Cache timestamp. :param remember: If True, saves permanent sessions. :param...
def get_user_by_token(self, user_id, token, token_ts=None, cache=None, cache_ts=None, remember=False, save_session=True):
if (self._user is not None): assert ((self._user is not _anon) and (self._user['user_id'] == user_id) and (self._user['token'] == token)) return self._user_or_none() if (cache and cache_ts): valid = self.store.validate_cache_timestamp(cache_ts, token_ts) if valid: sel...
'Returns a user based on password credentials. :param auth_id: Authentication id. :param password: User password. :param remember: If True, saves permanent sessions. :param save_session: If True, saves the user in the session if authentication succeeds. :param silent: If True, raises an exception if auth_id or password...
def get_user_by_password(self, auth_id, password, remember=False, save_session=True, silent=False):
if save_session: self.unset_session() self._user = self.store.validate_password(auth_id, password, silent=silent) if (not self._user): self._user = _anon elif save_session: self.set_session(self._user, remember=remember) return self._user_or_none()
'Auth session.'
@webapp2.cached_property def session(self):
return self.store.get_session(self.request)
'Saves a user in the session. :param user: A dictionary with user data. :param token: A unique token to be persisted. If None, a new one is created. :param token_ts: Token timestamp. If None, a new one is created. :param cache_ts: Token cache timestamp. If None, a new one is created. :remember: If True, session is set ...
def set_session(self, user, token=None, token_ts=None, cache_ts=None, remember=False, **session_args):
now = int(time.time()) token = (token or self.store.create_auth_token(user['user_id'])) token_ts = (token_ts or now) cache_ts = (cache_ts or now) if remember: max_age = self.store.config['token_max_age'] else: max_age = None session_args.setdefault('max_age', max_age) use...
'Removes a user from the session and invalidates the auth token.'
def unset_session(self):
self._user = None data = self.get_session_data(pop=True) if data: self.store.delete_auth_token(data['user_id'], data['token'])
'Returns the session data as a dictionary. :param pop: If True, removes the session. :returns: A deserialized session, or None.'
def get_session_data(self, pop=False):
func = (self.session.pop if pop else self.session.get) rv = func('_user', None) if (rv is not None): data = self.store.deserialize_session(rv) if data: return data elif (not pop): self.session.pop('_user', None) return None
'Sets the session data as a list. :param data: Deserialized session data. :param session_args: Extra arguments for the session.'
def set_session_data(self, data, **session_args):
data = self.store.serialize_session(data) if (data is not None): self.session['_user'] = data self.session.container.session_args.update(session_args)
'Initializes the Jinja2 object. :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):
self.config = config = app.config.load_config(self.config_key, default_values=default_config, user_values=config, required_keys=None) kwargs = config['environment_args'].copy() enable_i18n = ('jinja2.ext.i18n' in kwargs.get('extensions', [])) if ('loader' not in kwargs): template_path = config['...
'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):
return self.environment.get_template(_filename).render(**context)
'Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named `_foo.html` with the following contents: .. sourcecode:: html+jinja {% macro hello(name) %}Hello {{ name }}!{% endmacro %} You can access this from Python code like thi...
def get_template_attribute(self, filename, attribute):
template = self.environment.get_template(filename) return getattr(template.module, attribute)
'Returns a flash message. Flash messages are deleted when first read. :param key: Name of the flash key stored in the session. Default is \'_flash\'. :returns: The data stored in the flash, or an empty list.'
def get_flashes(self, key='_flash'):
return self.pop(key, [])
'Adds a flash message. Flash messages are deleted when first read. :param value: Value to be saved in the flash message. :param level: An optional level to set with the message. Default is `None`. :param key: Name of the flash key stored in the session. Default is \'_flash\'.'
def add_flash(self, value, level=None, key='_flash'):
self.setdefault(key, []).append((value, level))
'Check if a session id has the correct format.'
def _is_valid_sid(self, sid):
return (sid and (self._sid_re.match(sid) is not None))
'Initializes the session store. :param request: A :class:`webapp2.Request` instance. :param config: A dictionary of configuration values to be overridden. See the available keys in :data:`default_config`.'
def __init__(self, request, config=None):
self.request = request self.config = request.app.config.load_config(self.config_key, default_values=default_config, user_values=config, required_keys=('secret_key',)) self.sessions = {}
'Returns a configured session backend, importing it if needed. :param name: The backend keyword. :returns: A :class:`BaseSessionFactory` subclass.'
def get_backend(self, name):
backends = self.config['backends'] backend = backends[name] if isinstance(backend, basestring): backend = backends[name] = webapp2.import_string(backend) return backend
'Returns a session for a given name. If the session doesn\'t exist, a new session is returned. :param name: Cookie name. If not provided, uses the ``cookie_name`` value configured for this module. :param max_age: A maximum age in seconds for the session to be valid. Sessions store a timestamp to invalidate them if need...
def get_session(self, name=None, max_age=_default_value, factory=None, backend='securecookie'):
factory = (factory or self.get_backend(backend)) name = (name or self.config['cookie_name']) if (max_age is _default_value): max_age = self.config['session_max_age'] container = self._get_session_container(name, factory) return container.get_session(max_age=max_age)
'Returns a deserialized secure cookie value. :param name: Cookie name. :param max_age: Maximum age in seconds for a valid cookie. If the cookie is older than this, returns None. :returns: A secure cookie value or None if it is not set.'
def get_secure_cookie(self, name, max_age=_default_value):
if (max_age is _default_value): max_age = self.config['session_max_age'] value = self.request.cookies.get(name) if value: return self.serializer.deserialize(name, value, max_age=max_age)
'Sets a secure cookie to be saved. :param name: Cookie name. :param value: Cookie value. Must be a dictionary. :param kwargs: Options to save the cookie. See :meth:`get_session`.'
def set_secure_cookie(self, name, value, **kwargs):
assert isinstance(value, dict), 'Secure cookie values must be a dict.' container = self._get_session_container(name, SecureCookieSessionFactory) container.get_session().update(value) container.session_args.update(kwargs)
'Saves all sessions in a response object. :param response: A :class:`webapp.Response` object.'
def save_sessions(self, response):
for session in self.sessions.values(): session.save_session(response)
'Returns a session given a session id.'
def _get_by_sid(self, sid):
if self._is_valid_sid(sid): data = memcache.get(sid) if (data is not None): self.sid = sid return sessions.SessionDict(self, data=data) self.sid = self._get_new_sid() return sessions.SessionDict(self, new=True)
'Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.'
@classmethod def get_by_sid(cls, sid):
data = memcache.get(sid) if (not data): session = model.Key(cls, sid).get() if session: data = session.data memcache.set(sid, data) return data
'Saves the session and updates the memcache entry.'
def _put(self):
memcache.set(self._key.id(), self.data) super(Session, self).put()
'Returns a session given a session id.'
def _get_by_sid(self, sid):
if self._is_valid_sid(sid): data = self.session_model.get_by_sid(sid) if (data is not None): self.sid = sid return sessions.SessionDict(self, data=data) self.sid = self._get_new_sid() return sessions.SessionDict(self, new=True)
'Creates a new unique value. :param value: The value to be unique, as a string. The value should include the scope in which the value must be unique (ancestor, namespace, kind and/or property name). For example, for a unique property `email` from kind `User`, the value can be `User.email:me@myself.com`. In this case `U...
@classmethod def create(cls, value):
entity = cls(key=model.Key(cls, value)) txn = (lambda : (entity.put() if (not entity.key.get()) else None)) return (model.transaction(txn) is not None)
'Creates multiple unique values at once. :param values: A sequence of values to be unique. See :meth:`create`. :returns: A tuple (bool, list_of_keys). If all values were created, bool is True and list_of_keys is empty. If one or more values weren\'t created, bool is False and the list contains all the values that alrea...
@classmethod def create_multi(cls, values):
keys = [model.Key(cls, value) for value in values] entities = [cls(key=key) for key in keys] func = (lambda e: (e.put() if (not e.key.get()) else None)) created = [model.transaction((lambda : func(e))) for e in entities] if (created != keys): model.delete_multi((k for k in created if k)) ...
'Deletes multiple unique values at once. :param values: A sequence of values to be deleted.'
@classmethod def delete_multi(cls, values):
return model.delete_multi((model.Key(cls, v) for v in values))
'Returns a token key. :param user: User unique ID. :param subject: The subject of the key. Examples: - \'auth\' - \'signup\' :param token: Randomly generated token. :returns: ``model.Key`` containing a string id in the following format: ``{user_id}.{subject}.{token}.``'
@classmethod def get_key(cls, user, subject, token):
return model.Key(cls, ('%s.%s.%s' % (str(user), subject, token)))
'Creates a new token for the given user. :param user: User unique ID. :param subject: The subject of the key. Examples: - \'auth\' - \'signup\' :param token: Optionally an existing token may be provided. If None, a random token will be generated. :returns: The newly created :class:`UserToken`.'
@classmethod def create(cls, user, subject, token=None):
user = str(user) token = (token or security.generate_random_string(entropy=128)) key = cls.get_key(user, subject, token) entity = cls(key=key, user=user, subject=subject, token=token) entity.put() return entity
'Fetches a user token. :param user: User unique ID. :param subject: The subject of the key. Examples: - \'auth\' - \'signup\' :param token: The existing token needing verified. :returns: A :class:`UserToken` or None if the token does not exist.'
@classmethod def get(cls, user=None, subject=None, token=None):
if (user and subject and token): return cls.get_key(user, subject, token).get() assert (subject and token), 'subject and token must be provided to UserToken.get().' return cls.query((cls.subject == subject), (cls.token == token)).get()
'Returns this user\'s unique ID, which can be an integer or string.'
def get_id(self):
return self._key.id()
'Returns a user object based on a auth_id. :param auth_id: String representing a unique id for the user. Examples: - own:username - google:username :returns: A user object.'
@classmethod def get_by_auth_id(cls, auth_id):
return cls.query((cls.auth_ids == auth_id)).get()
'Returns a user object based on a user ID and token. :param user_id: The user_id of the requesting user. :param token: The token string to be verified. :returns: A tuple ``(User, timestamp)``, with a user object and the token timestamp, or ``(None, None)`` if both were not found.'
@classmethod def get_by_auth_token(cls, user_id, token):
token_key = cls.token_model.get_key(user_id, 'auth', token) user_key = model.Key(cls, user_id) (valid_token, user) = model.get_multi([token_key, user_key]) if (valid_token and user): timestamp = int(time.mktime(valid_token.created.timetuple())) return (user, timestamp) return (None, ...
'Returns a user object, validating password. :param auth_id: Authentication id. :param password: Password to be checked. :returns: A user object, if found and password matches. :raises: ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.'
@classmethod def get_by_auth_password(cls, auth_id, password):
user = cls.get_by_auth_id(auth_id) if (not user): raise auth.InvalidAuthIdError() if (not security.check_password_hash(password, user.password)): raise auth.InvalidPasswordError() return user