desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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 value = Cookie._unquote(value) 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 sig...
'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()
'A helper method to add additional auth ids to a User :param auth_id: String representing a unique id for the user. Examples: - own:username - google:username :returns: A tuple (boolean, info). The boolean indicates if the user was saved. If creation succeeds, ``info`` is the user entity; otherwise it is a list of dupl...
def add_auth_id(self, auth_id):
self.auth_ids.append(auth_id) unique = ('%s.auth_id:%s' % (self.__class__.__name__, auth_id)) ok = self.unique_model.create(unique) if ok: self.put() return (True, self) else: return (False, ['auth_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
'Checks for existence of a token, given user_id, subject and token. :param user_id: User unique ID. :param subject: The subject of the key. Examples: - \'auth\' - \'signup\' :param token: The token string to be validated. :returns: A :class:`UserToken` or None if the token does not exist.'
@classmethod def validate_token(cls, user_id, subject, token):
return (cls.token_model.get(user=user_id, subject=subject, token=token) is not None)
'Creates a new authorization token for a given user ID. :param user_id: User unique ID. :returns: A string with the authorization token.'
@classmethod def create_auth_token(cls, user_id):
return cls.token_model.create(user_id, 'auth').token
'Deletes a given authorization token. :param user_id: User unique ID. :param token: A string with the authorization token.'
@classmethod def delete_auth_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'auth', token).delete()
'Creates a new user. :param auth_id: A string that is unique to the user. Users may have multiple auth ids. Example auth ids: - own:username - own:email@example.com - google:username - yahoo:username The value of `auth_id` must be unique. :param unique_properties: Sequence of extra property names that must be unique. :...
@classmethod def create_user(cls, auth_id, unique_properties=None, **user_values):
assert (user_values.get('password') is None), 'Use password_raw instead of password to create new users.' assert (not isinstance(auth_id, list)), 'Creating a user with multiple auth_ids is not allowed, please provide a single auth_id.' if ('pass...
'Initializes a URL route. :param template: A route template to match against ``environ[\'SERVER_NAME\']``. See a syntax description in :meth:`webapp2.Route.__init__`. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, template, routes):
super(DomainRoute, self).__init__(routes) self.template = template
'Initializes a URL route. :param prefix: The prefix to be prepended. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, prefix, routes):
super(NamePrefixRoute, self).__init__(routes) self.prefix = prefix for route in self.get_routes(): setattr(route, self._attr, (prefix + getattr(route, self._attr)))
'Initializes a URL route. :param prefix: The prefix to be prepended. It must start with a slash but not end with a slash. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, prefix, routes):
assert (prefix.startswith('/') and (not prefix.endswith('/'))), 'Path prefixes must start with a slash but not end with a slash.' super(PathPrefixRoute, self).__init__(prefix, routes)
'Initializes a URL route. Extra arguments compared to :meth:`webapp2.Route.__init__`: :param redirect_to: A URL string or a callable that returns a URL. If set, this route is used to redirect to it. The callable is called passing ``(handler, *args, **kwargs)`` as arguments. This is a convenience to use :class:`Redirect...
def __init__(self, template, handler=None, name=None, defaults=None, build_only=False, handler_method=None, methods=None, schemes=None, redirect_to=None, redirect_to_name=None, strict_slash=False):
super(RedirectRoute, self).__init__(template, handler=handler, name=name, defaults=defaults, build_only=build_only, handler_method=handler_method, methods=methods, schemes=schemes) if (strict_slash and (not name)): raise ValueError('Routes with strict_slash must have a name.') self...
'Generator to get all routes that can be matched from a route. :yields: This route or all nested routes that can be matched.'
def get_match_routes(self):
if self.redirect_to_name: main_route = self._get_redirect_route(name=self.redirect_to_name) else: main_route = self if (not self.build_only): if (self.strict_slash is True): if self.template.endswith('/'): template = self.template[:(-1)] else: ...
'Test multi_int and multi_float flags.'
def testMultiNumericalFlags(self):
int_defaults = [77, 88] gflags.DEFINE_multi_int('m_int', int_defaults, 'integer option that can occur multiple times', short_name='mi') self.assertListEqual(FLAGS.get('m_int', None), int_defaults) argv = ('./program', '--m_int=-99', '--mi=101') FLAGS(argv) self.assertListEqual(...
'Test multi_int and multi_float flags with a single default value.'
def testSingleValueDefault(self):
int_default = 77 gflags.DEFINE_multi_int('m_int1', int_default, 'integer option that can occur multiple times') self.assertListEqual(FLAGS.get('m_int1', None), [int_default]) float_default = 2.2 gflags.DEFINE_multi_float('m_float1', float_default, 'float option that can ...
'Test multi_int and multi_float flags with non-parseable values.'
def testBadMultiNumericalFlags(self):
self.assertRaisesWithRegexpMatch(gflags.IllegalFlagValue, "flag --m_int2=abc: invalid literal for int\\(\\) with base 10: 'abc'", gflags.DEFINE_multi_int, 'm_int2', ['abc'], 'desc') self.assertRaisesWithRegexpMatch(gflags.IllegalFlagValue, 'flag --m_float2=abc: invalid litera...
'Creates and sets up some dummy flagfile files with bogus flags'
def _SetupTestFiles(self):
tmp_path = '/tmp/flags_unittest' if os.path.exists(tmp_path): shutil.rmtree(tmp_path) os.makedirs(tmp_path) try: tmp_flag_file_1 = open((tmp_path + '/UnitTestFile1.tst'), 'w') tmp_flag_file_2 = open((tmp_path + '/UnitTestFile2.tst'), 'w') tmp_flag_file_3 = open((tmp_path ...
'Closes the files we just created. tempfile deletes them for us'
def _RemoveTestFiles(self):
for file_name in self.files_to_delete: try: os.remove(file_name) except OSError as e_msg: print ('%s\n, Problem deleting test file' % e_msg)
'Test trivial case with no flagfile based options.'
def testMethod_flagfiles_1(self):
fake_cmd_line = 'fooScript --UnitTestBoolFlag' fake_argv = fake_cmd_line.split(' ') self.flag_values(fake_argv) self.assertEqual(self.flag_values.UnitTestBoolFlag, 1) self.assertEqual(fake_argv, self._ReadFlagsFromFiles(fake_argv, False))
'Tests parsing one file + arguments off simulated argv'
def testMethod_flagfiles_2(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --q --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--q', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag'] test_results = self._ReadFlagsFro...
'Tests parsing nested files + arguments of simulated argv'
def testMethod_flagfiles_3(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --UnitTestNumber=77 --flagfile=%s' % tmp_files[1]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--UnitTestNumber=77', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag', '--Un...
'Tests parsing self-referential files + arguments of simulated argv. This test should print a warning to stderr of some sort.'
def testMethod_flagfiles_4(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --flagfile=%s --noUnitTestBoolFlag' % tmp_files[2]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--UnitTestMessage1=setFromTempFile3', '--UnitTestBoolFlag', '--noUnitTestBoolFlag'] test_results = self._...
'Test that --flagfile parsing respects the \'--\' end-of-options marker.'
def testMethod_flagfiles_5(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag -- --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', '--', ('--flagfile=%s' % tmp_files[0])] test_results = self._ReadFlagsFromFiles(fake_argv, False...
'Test that --flagfile parsing stops at non-options (non-GNU behavior).'
def testMethod_flagfiles_6(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', ('--flagfile=%s' % tmp_files[0])] test_results = self._ReadFlagsFromFiles(fake...
'Test that --flagfile parsing skips over a non-option (GNU behavior).'
def testMethod_flagfiles_7(self):
self.flag_values.UseGnuGetOpt() tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', '--UnitTestMessage1=tempFile1!', '--UnitTestNu...
'Test that --flagfile parsing respects force_gnu=True.'
def testMethod_flagfiles_8(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[0]) fake_argv = fake_cmd_line.split(' ') expected_results = ['fooScript', '--SomeFlag', 'some_arg', '--UnitTestMessage1=tempFile1!', '--UnitTestNumber=54321', '--noUnitTestBoolFlag']...
'Test that --flagfile raises except on file that is unreadable.'
def testMethod_flagfiles_NoPermissions(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s' % tmp_files[3]) fake_argv = fake_cmd_line.split(' ') self.assertRaises(gflags.CantOpenFlagFileError, self._ReadFlagsFromFiles, fake_argv, True)
'Test that --flagfile raises except on file that does not exist.'
def testMethod_flagfiles_NotFound(self):
tmp_files = self._SetupTestFiles() fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%sNOTEXIST' % tmp_files[3]) fake_argv = fake_cmd_line.split(' ') self.assertRaises(gflags.CantOpenFlagFileError, self._ReadFlagsFromFiles, fake_argv, True)
'Test that user directory referenced paths (ie. ~/foo) are correctly expanded. This test depends on whatever account\'s running the unit test to have read/write access to their own home directory, otherwise it\'ll FAIL.'
def test_flagfiles_user_path_expansion(self):
fake_flagfile_item_style_1 = '--flagfile=~/foo.file' fake_flagfile_item_style_2 = '-flagfile=~/foo.file' expected_results = os.path.expanduser('~/foo.file') test_results = self.flag_values.ExtractFilename(fake_flagfile_item_style_1) self.assertEqual(expected_results, test_results) test_results =...
'Test that the flags parser does not mutilate arguments which are not supposed to be flags'
def test_no_touchy_non_flags(self):
fake_argv = ['fooScript', '--UnitTestBoolFlag', 'command', '--command_arg1', '--UnitTestBoom', '--UnitTestB'] argv = self.flag_values(fake_argv) self.assertEqual(argv, (fake_argv[:1] + fake_argv[2:]))
'Test that flags given after arguments are parsed if using gnu_getopt.'
def test_parse_flags_after_args_if_using_gnu_getopt(self):
self.flag_values.UseGnuGetOpt() fake_argv = ['fooScript', '--UnitTestBoolFlag', 'command', '--UnitTestB'] argv = self.flag_values(fake_argv) self.assertEqual(argv, ['fooScript', 'command'])
'Test changing flag defaults.'
def test_SetDefault(self):
self.flag_values['UnitTestMessage1'].SetDefault('New value') self.assertEqual(self.flag_values.UnitTestMessage1, 'New value') self.assertEqual(self.flag_values['UnitTestMessage1'].default_as_str, "'New value'") self.flag_values(['dummyscript', '--UnitTestMessage1=Newer value']) self.asse...
'Test FlagValues.ShortestUniquePrefixes'
def testMethod_ShortestUniquePrefixes(self):
gflags.DEFINE_string('a', '', '', flag_values=self.flag_values) gflags.DEFINE_string('abc', '', '', flag_values=self.flag_values) gflags.DEFINE_string('common_a_string', '', '', flag_values=self.flag_values) gflags.DEFINE_boolean('common_b_boolean', 0, '', flag_values=self.flag_values) gflags.DEFINE...
'Test use of non-global FlagValues'
def test_nonglobal_flags(self):
nonglobal_flags = gflags.FlagValues() gflags.DEFINE_string('nonglobal_flag', 'Bob', 'flaghelp', nonglobal_flags) argv = ('./program', '--nonglobal_flag=Mary', 'extra') argv = nonglobal_flags(argv) assert (len(argv) == 2), 'wrong number of arguments pulled' assert (argv[0] == './progr...
'Test unrecognized non-global flags'
def test_unrecognized_nonglobal_flags(self):
nonglobal_flags = gflags.FlagValues() argv = ('./program', '--nosuchflag') try: argv = nonglobal_flags(argv) raise AssertionError('Unknown flag exception not raised') except gflags.UnrecognizedFlag as e: assert (e.flagname == 'nosuchflag') pass argv = ('./...
'Checks that del self.flag_values.flag_id works.'
def testFlagValuesDelAttr(self):
default_value = 'default value for testFlagValuesDelAttr' flag_values = gflags.FlagValues() gflags.DEFINE_string('delattr_foo', default_value, 'A simple flag.', flag_values=flag_values) self.assertEquals(flag_values.delattr_foo, default_value) flag_obj = flag_values['delattr_foo'] ...
'Returns the list of names of flags defined by a module. Auxiliary for the testKeyFlags* methods. Args: module: A module object or a string module name. flag_values: A FlagValues object. Returns: A list of strings.'
def _GetNamesOfDefinedFlags(self, module, flag_values):
return [f.name for f in flag_values._GetFlagsDefinedByModule(module)]