1.24. utilities

This module collects various useful utility functions that are used throughout the application.

1.24.1. Functions

argp_add_args(parser, default_root='')[source]

Add standard arguments to a new argparse.ArgumentParser instance for configuring logging options from the command line and displaying the version information.

Note

This function installs a hook to parser.parse_args to automatically handle options which it adds. This includes setting up a stream logger based on the added options.

Parameters:
assert_arg_type(arg, arg_type, arg_pos=1, func_name=None)[source]

Check that an argument is an instance of the specified type and if not raise a TypeError exception with a meaningful message. If func_name is not specified, it will be determined by examining the stack.

Parameters:
  • arg – The argument to check.
  • arg_type (list, tuple, type) – The type or sequence of types that arg can be.
  • arg_pos (int) – The position of the argument in the function.
  • func_name (str) – The name of the function the argument is for.
configure_stream_logger(logger, level=None)[source]

Configure the default stream handler for logging messages to the console. This also configures the basic logging environment for the application.

Parameters:
  • logger (str) – The logger to add the stream handler for.
  • level (None, int, str) – The level to set the logger to, will default to WARNING if no level is specified.
Returns:

The new configured stream handler.

Return type:

logging.StreamHandler

datetime_local_to_utc(dt)[source]

Convert a datetime.datetime instance from the local time to UTC time.

Parameters:dt (datetime.datetime) – The time to convert from local to UTC.
Returns:The time converted to the UTC timezone.
Return type:datetime.datetime
datetime_utc_to_local(dt)[source]

Convert a datetime.datetime instance from UTC time to the local time.

Parameters:dt (datetime.datetime) – The time to convert from UTC to local.
Returns:The time converted to the local timezone.
Return type:datetime.datetime
format_datetime(dt, encoding='utf-8')[source]

Format a date time object into a string. If the object dt is not an instance of datetime.datetime then an empty string will be returned.

Parameters:
  • dt (datetime.datetime) – The object to format.
  • encoding (str) – The encoding to use to coerce the return value into a unicode string.
Returns:

The string representing the formatted time.

Return type:

str

is_valid_email_address(email_address)[source]

Check that the string specified appears to be a valid email address.

Parameters:email_address (str) – The email address to validate.
Returns:Whether the email address appears to be valid or not.
Return type:bool
make_message_uid(upper=True, lower=True, digits=True)[source]

Creates a random string of specified character set to be used as a message id. At least one of upper, lower, or digits must be True.

Parameters:
  • upper (bool) – Include upper case characters in the UID.
  • lower (bool) – Include lower case characters in the UID.
  • digits (bool) – Include digits in the UID.
Returns:

String of characters from the random_string function.

Return type:

str

make_webrelpath(path)[source]

Forcefully make path into a web-suitable relative path. This will strip off leading and trailing directory separators.

New in version 1.14.0.

Parameters:path (str) – The path to convert into a web-suitable relative path.
Returns:The converted path.
Return type:str
make_visit_uid()[source]

Creates a random string of characters and numbers to be used as a visit id.

Returns:String of characters from the random_string function.
Return type:str
nonempty_string(value)[source]

Convert value into either a non-empty string or None. This will also strip leading and trailing whitespace.

Parameters:value (str) – The value to convert.
Returns:Either the non-empty string or None.
open_uri(uri)[source]

Open a URI in a platform intelligent way. On Windows this will use ‘cmd.exe /c start’ and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised.

Parameters:uri (str) – The URI to open.
parse_datetime(ts)[source]

Parse a time stamp into a datetime.datetime instance. The time stamp must be in a compatible format, as would have been returned from the format_datetime() function.

Parameters:ts (str) – The timestamp to parse.
Returns:The parsed timestamp.
Return type:datetime.datetime
password_is_complex(password, min_len=12)[source]

Check that the specified string meets standard password complexity requirements. :param str password: The password to validate. :param int min_len: The minimum length the password should be. :return: Whether the strings appears to be complex or not. :rtype: bool

random_string(size, charset=None)[source]

Generate a random string consisting of uppercase letters, lowercase letters and numbers of the specified size.

Parameters:size (int) – The size of the string to make.
Returns:The string containing the random characters.
Return type:str
random_string_lower_numeric(size)[source]

Generate a random string consisting of lowercase letters and numbers of the specified size.

Parameters:size (int) – The size of the string to make.
Returns:The string containing the random characters.
Return type:str
switch(value, comp=<built-in function eq>, swapped=False)[source]

A pure Python implementation of a switch case statement. comp will be used as a comparison function and passed two arguments of value and the provided case respectively.

Switch case example usage:

for case in switch(2):
    if case(1):
        print('case 1 matched!')
        break
    if case(2):
        print('case 2 matched!')
        break
else:
    print('no cases were matched')
Parameters:
  • value – The value to compare in each of the case statements.
  • comp – The function to use for comparison in the case statements.
  • swapped – Whether or not to swap the arguments to the comp function.
Returns:

A function to be called for each case statement.

validate_json_schema(data, schema_file_id)[source]

Validate the specified data against the specified schema. The schema file will be searched for and loaded based on it’s id. If the validation fails a ValidationError will be raised.

Parameters:
  • data – The data to validate against the schema.
  • schema_file_id – The id of the schema to load.

1.24.2. Classes

class Event[source]

Bases: threading.Event

clear()[source]

Reset the internal flag to false.

Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

set()[source]

Set the internal flag to true.

All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.

wait(timeout=None)[source]

Block until the internal flag is true.

If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.

class FreezableDict(*args, **kwargs)[source]

Bases: collections.OrderedDict

A dictionary that can be frozen to prevent further editing. Useful for debugging. If any function tries to edit a frozen dictionary, a RuntimeError will be raised and a traceback will occur.

clear() → None. Remove all items from od.[source]
freeze()[source]

Freeze the dictionary to prevent further editing.

frozen[source]

Whether or not the dictionary is frozen and can not be modified.

Return type:bool
pop(k[, d]) → v, remove specified key and return the corresponding[source]

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem(*args, **kwargs)[source]

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

thaw()[source]

Thaw the dictionary to once again enable editing.

update([E, ]**F) → None. Update D from dict/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

class PrefixLoggerAdapter(prefix, *args, **kwargs)[source]

Bases: logging.LoggerAdapter

A log adapter that simply prefixes the specified string to all messages. A single space will be inserted between the prefix and the message.

__init__(prefix, *args, **kwargs)[source]
Parameters:prefix (str) – The string to prefix all messages with.
process(message, kwargs)[source]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

class Mock(*args, **kwargs)[source]

Bases: object

A fake object used to replace missing imports when generating documentation.

class Thread(target=None, name=None, args=(), kwargs=None, **_kwargs)[source]

King Phisher’s base threading class with two way events.