keystonemiddleware.openstack.common package

Submodules

keystonemiddleware.openstack.common.gettextutils module

gettext for openstack-common modules.

Usual usage in an openstack.common module:

from keystonemiddleware.openstack.common.gettextutils import _
class keystonemiddleware.openstack.common.gettextutils.Message

Bases: unicode

A Message object is a unicode object that can be translated.

Translation of Message is done explicitly using the translate() method. For all non-translation intents and purposes, a Message is simply unicode, and can be treated as such.

translate(desired_locale=None)

Translate this message to the desired locale.

Parameters:desired_locale – The desired locale to translate the message to, if no locale is provided the message will be translated to the system’s default locale.
Returns:the translated message in unicode
class keystonemiddleware.openstack.common.gettextutils.TranslationHandler(locale=None, target=None)

Bases: logging.handlers.MemoryHandler

Handler that translates records before logging them.

The TranslationHandler takes a locale and a target logging.Handler object to forward LogRecord objects to after translating them. This handler depends on Message objects being logged, instead of regular strings.

The handler can be configured declaratively in the logging.conf as follows:

[handlers] keys = translatedlog, translator

[handler_translatedlog] class = handlers.WatchedFileHandler args = (‘/var/log/api-localized.log’,) formatter = context

[handler_translator] class = openstack.common.log.TranslationHandler target = translatedlog args = (‘zh_CN’,)

If the specified locale is not available in the system, the handler will log in the default locale.

emit(record)
setFormatter(fmt)
class keystonemiddleware.openstack.common.gettextutils.TranslatorFactory(domain, lazy=False, localedir=None)

Bases: object

Create translator functions

log_critical

Translate critical-level log messages.

log_error

Translate error-level log messages.

log_info

Translate info-level log messages.

log_warning

Translate warning-level log messages.

primary

The default translation function.

keystonemiddleware.openstack.common.gettextutils.enable_lazy()

Convenience function for configuring _() to use lazy gettext

Call this at the start of execution to enable the gettextutils._ function to use lazy gettext functionality. This is useful if your project is importing _ directly instead of using the gettextutils.install() way of importing the _ function.

keystonemiddleware.openstack.common.gettextutils.get_available_languages(domain)

Lists the available languages for the given translation domain.

Parameters:domain – the domain to get languages for
keystonemiddleware.openstack.common.gettextutils.install(domain, lazy=False)

Install a _() function using the given translation domain.

Given a translation domain, install a _() function using gettext’s install() function.

The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specific environment variable (e.g. NOVA_LOCALEDIR).

Parameters:
  • domain – the translation domain
  • lazy – indicates whether or not to install the lazy _() function. The lazy _() introduces a way to do deferred translation of messages by installing a _ that builds Message objects, instead of strings, which can then be lazily translated into any available locale.
keystonemiddleware.openstack.common.gettextutils.translate(obj, desired_locale=None)

Gets the translated unicode representation of the given object.

If the object is not translatable it is returned as-is. If the locale is None the object is translated to the system locale.

Parameters:
  • obj – the object to translate
  • desired_locale – the locale to translate the message to, if None the default system locale will be used
Returns:

the translated object in unicode, or the original object if it could not be translated

keystonemiddleware.openstack.common.importutils module

Import related utilities and helper functions.

keystonemiddleware.openstack.common.importutils.import_class(import_str)

Returns a class from a string including module and class.

keystonemiddleware.openstack.common.importutils.import_module(import_str)

Import a module.

keystonemiddleware.openstack.common.importutils.import_object(import_str, *args, **kwargs)

Import a class and return an instance of it.

keystonemiddleware.openstack.common.importutils.import_object_ns(name_space, import_str, *args, **kwargs)

Tries to import object from default namespace.

Imports a class and return an instance of it, first by trying to find the class in a default namespace, then failing back to a full path if not found in the default namespace.

keystonemiddleware.openstack.common.importutils.import_versioned_module(version, submodule=None)
keystonemiddleware.openstack.common.importutils.try_import(import_str, default=None)

Try to import a module and if it fails return default.

keystonemiddleware.openstack.common.jsonutils module

JSON related utilities.

This module provides a few things:

1) A handy function for getting an object down to something that can be JSON serialized. See to_primitive().

2) Wrappers around loads() and dumps(). The dumps() wrapper will automatically use to_primitive() for you if needed.

3) This sets up anyjson to use the loads() and dumps() wrappers if anyjson is available.

keystonemiddleware.openstack.common.jsonutils.dumps(value, default=<function to_primitive at 0x7ff82d4fe500>, **kwargs)
keystonemiddleware.openstack.common.jsonutils.load(fp, encoding='utf-8', **kwargs)
keystonemiddleware.openstack.common.jsonutils.loads(s, encoding='utf-8', **kwargs)
keystonemiddleware.openstack.common.jsonutils.to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3)

Convert a complex object into primitives.

Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures.

To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are hashable. Instead we just track the depth of the object inspections and don’t go too deep.

Therefore, convert_instances=True is lossy ... be aware.

keystonemiddleware.openstack.common.memorycache module

Super simple fake memcache client.

class keystonemiddleware.openstack.common.memorycache.Client(*args, **kwargs)

Bases: object

Replicates a tiny subset of memcached client interface.

add(key, value, time=0, min_compress_len=0)

Sets the value for a key if it doesn’t exist.

delete(key, time=0)

Deletes the value associated with a key.

get(key)

Retrieves the value for a key or None.

This expunges expired keys during each get.

incr(key, delta=1)

Increments the value for a key.

set(key, value, time=0, min_compress_len=0)

Sets the value for a key.

keystonemiddleware.openstack.common.memorycache.get_client(memcached_servers=None)

keystonemiddleware.openstack.common.strutils module

System-level utilities and helper functions.

keystonemiddleware.openstack.common.strutils.bool_from_string(subject, strict=False, default=False)

Interpret a string as a boolean.

A case-insensitive match is performed such that strings matching ‘t’, ‘true’, ‘on’, ‘y’, ‘yes’, or ‘1’ are considered True and, when strict=False, anything else returns the value specified by ‘default’.

Useful for JSON-decoded stuff and config file parsing.

If strict=True, unrecognized values, including None, will raise a ValueError which is useful when parsing values passed in from an API call. Strings yielding False are ‘f’, ‘false’, ‘off’, ‘n’, ‘no’, or ‘0’.

keystonemiddleware.openstack.common.strutils.int_from_bool_as_string(subject)

Interpret a string as a boolean and return either 1 or 0.

Any string value in:

(‘True’, ‘true’, ‘On’, ‘on’, ‘1’)

is interpreted as a boolean True.

Useful for JSON-decoded stuff and config file parsing

keystonemiddleware.openstack.common.strutils.safe_decode(text, incoming=None, errors='strict')
Decodes incoming text/bytes string using incoming if they’re not
already unicode.
Parameters:
Returns:

text or a unicode incoming encoded representation of it.

Raises TypeError:
 

If text is not an instance of str

keystonemiddleware.openstack.common.strutils.safe_encode(text, incoming=None, encoding='utf-8', errors='strict')

Encodes incoming text/bytes string using encoding.

If incoming is not specified, text is expected to be encoded with current python’s default encoding. (sys.getdefaultencoding)

Parameters:
Returns:

text or a bytestring encoding encoded representation of it.

Raises TypeError:
 

If text is not an instance of str

keystonemiddleware.openstack.common.strutils.string_to_bytes(text, unit_system='IEC', return_int=False)

Converts a string into an float representation of bytes.

The units supported for IEC

Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it)
KB, KiB, MB, MiB, GB, GiB, TB, TiB

The units supported for SI

kb(it), Mb(it), Gb(it), Tb(it)
kB, MB, GB, TB

Note that the SI unit system does not support capital letter ‘K’

Parameters:
  • text – String input for bytes size conversion.
  • unit_system – Unit system for byte size conversion.
  • return_int – If True, returns integer representation of text in bytes. (default: decimal)
Returns:

Numerical representation of text in bytes.

Raises ValueError:
 

If text has an invalid value.

keystonemiddleware.openstack.common.strutils.to_slug(value, incoming=None, errors='strict')

Normalize string.

Convert to lowercase, remove non-word characters, and convert spaces to hyphens.

Inspired by Django’s slugify filter.

Parameters:
Returns:

slugified unicode representation of value

Raises TypeError:
 

If text is not an instance of str

keystonemiddleware.openstack.common.timeutils module

Time related utilities and helper functions.

keystonemiddleware.openstack.common.timeutils.advance_time_delta(timedelta)

Advance overridden time using a datetime.timedelta.

keystonemiddleware.openstack.common.timeutils.advance_time_seconds(seconds)

Advance overridden time by seconds.

keystonemiddleware.openstack.common.timeutils.clear_time_override()

Remove the overridden time.

keystonemiddleware.openstack.common.timeutils.delta_seconds(before, after)

Return the difference between two timing objects.

Compute the difference in seconds between two date, time, or datetime objects (as a float, to microsecond resolution).

keystonemiddleware.openstack.common.timeutils.is_newer_than(after, seconds)

Return True if after is newer than seconds.

keystonemiddleware.openstack.common.timeutils.is_older_than(before, seconds)

Return True if before is older than seconds.

keystonemiddleware.openstack.common.timeutils.is_soon(dt, window)

Determines if time is going to happen in the next window seconds.

Parameters:
  • dt – the time
  • window – minimum seconds to remain to consider the time not soon
Returns:

True if expiration is within the given duration

keystonemiddleware.openstack.common.timeutils.iso8601_from_timestamp(timestamp)

Returns an iso8601 formatted date from timestamp.

keystonemiddleware.openstack.common.timeutils.isotime(at=None, subsecond=False)

Stringify time in ISO 8601 format.

keystonemiddleware.openstack.common.timeutils.marshall_now(now=None)

Make an rpc-safe datetime with microseconds.

Note: tzinfo is stripped, but not required for relative times.

keystonemiddleware.openstack.common.timeutils.normalize_time(timestamp)

Normalize time in arbitrary timezone to UTC naive object.

keystonemiddleware.openstack.common.timeutils.parse_isotime(timestr)

Parse time from ISO 8601 format.

keystonemiddleware.openstack.common.timeutils.parse_strtime(timestr, fmt='%Y-%m-%dT%H:%M:%S.%f')

Turn a formatted time back into a datetime.

keystonemiddleware.openstack.common.timeutils.set_time_override(override_time=None)

Overrides utils.utcnow.

Make it return a constant time or a list thereof, one at a time.

Parameters:override_time – datetime instance or list thereof. If not given, defaults to the current UTC time.
keystonemiddleware.openstack.common.timeutils.strtime(at=None, fmt='%Y-%m-%dT%H:%M:%S.%f')

Returns formatted utcnow.

keystonemiddleware.openstack.common.timeutils.total_seconds(delta)

Return the total seconds of datetime.timedelta object.

Compute total seconds of datetime.timedelta, datetime.timedelta doesn’t have method total_seconds in Python2.6, calculate it manually.

keystonemiddleware.openstack.common.timeutils.unmarshall_time(tyme)

Unmarshall a datetime dict.

keystonemiddleware.openstack.common.timeutils.utcnow()

Overridable version of utils.utcnow.

keystonemiddleware.openstack.common.timeutils.utcnow_ts()

Timestamp version of our utcnow function.

Module contents