chapps.util module

Utility classes

Since CHAPPS mainly deals with policy requests coming from Postfix, there is a utility object for representing them in a way which makes the code easier to read while also providing access optimizations.

There is another utility class for providing the configuration data via an object which presents dictionary keys as attributes.

In order to create different defaults and access documentation files, an object is provided which detects whether the library is running within a virtual environment, and serves as a source of local paths to package resources.

chapps.util.hash_password(password, encoding='utf-8')[source]
Return type


  • password (str) –

  • encoding (str) –

class chapps.util.VenvDetector[source]

Bases: object

Detect use of a virtual environment and calculate local paths

The detector encapsulates the job of determining whether a virtual environment is activated, and assists in composing some important paths in order to locate certain files the application needs.

One of those files is Markdown source which is imported into the live API documentation. Another is the config file.

Instance attributes:


Path pointing at location where data files are installed


bool indicating whether a virtual environment is active


Path pointing at the location of the Markdown


Path pointing at the config file


Path to the root of the active virtual environment, or None if none is active

__init__(*, datapath=None)[source]

Detect virtual environments and provide local package paths


datapath (Union[str, Path, None]) – optional override to point at the data installation path of the package (or a surrogate). The API uses this value to load the API readme into the live docs.


Return the non-virtual base prefix

Sometimes called sys.real_prefix, so we check for both.


the base path prefix

Return type



Compare prefixes to determine if a virtual environment is active.


true if a virtual environment is active, otherwise False

Return type



Determine whether invoked by Sphinx

Return type



True if Sphinx invoked the library

property ve: bool

Property which memoizes in_virtualenv()

Return type


property sb: bool

Property which memoizes sphinx_build()

Return type


property docpath: pathlib.Path

Memoizes the documentation location


a Path pointing at the Markdown files’ location

Return type


property confpath: pathlib.Path

Memoizes the config file’s full path


a Path pointing at the config file

Return type


property venvpath: Optional[pathlib.Path]

The virtual environment root, if any


None or the value of sys.prefix as a Path

Return type


If no virtual environment is active, then None is returned, otherwise a Path instance is returned, containing the path to the virtual environment. This hasn’t been tested with all types of virtual environment.

class chapps.util.AttrDict[source]


Attribute Dictionary

This simple class allows accessing the keys of a hash as attributes on an object. As a useful side effect it also casts floats, integers and booleans in advance.

This object is used in CHAPPSConfig for holding the configuration data.


The purpose of this class is to map all the keys of a fairly small dict as attributes of the instance onto their values in the source dict. This class does not perform the same sort of lazy-loading as the PostfixPolicyRequest class below; it pre-maps all the elements in the source dict. So be careful about passing large dictionaries to it.


Given the stated purpose of the class, all internal instance attributes, i.e. ones not associated to a key-value pair in the source object, should begin with _ (an underscore).

boolean_pattern = re.compile('^[Tt]rue|[Ff]alse$')

A regex to detect text-string boolean values

__init__(data=None, **kwargs)[source]

Populate an instance with attributes


If, and only if, data is not provided, then the keyword arguments will be used in place of data provided as a dict.

Henceforth whatever is rounded up to use shall be referred to as the data.

The initialization routine creates an attribute on the instance for each key in the data, and then attempts to cast the value:

  1. to an int.

  2. If a TypeError is encountered, the unadulterated value is used.

  3. If only ValueError is raised, then it is casted to float

  4. if that causes another ValueError then it is matched against the boolean_pattern to see whether it matches, which is to say, whether it is a string containing “true” or “false”.

  5. If so, a simple check is conducted to determine whether the match was four characters long: True.

  6. If it does not test positive for truth, it is considered to be False.

  7. But if it wasn’t a match for the boolean_pattern at all, then its original value is preserved.

Generally, instances of this class are used to present a particular module, such as a policy manager, with its configuration in a form which can be dereferenced with dot notation. As such, values which cannot be casted to some other type are almost always left in their original form as strings, because the AttrDict is being initialized with a sub-block of a ConfigParser as the source object, and its values will all be strings.

keys() a set-like object providing a view on D's keys[source]
class chapps.util.PostfixPolicyRequest[source]


Lazy-loading Policy Request Mapping Interface

An implementation of Mapping which by default only processes and caches values from the data payload when they are accessed, to avoid a bunch of useless parsing. Instances may be dereferenced like hashes, but the keys are also attributes on the instance, so they can be accessed without brackets and quotation marks.

Once parsed, results are memoized.

For example, a payload might look a bit like this, when it is first received from Postfix and turned into an array of one string per line:

payload = [

Refer to the Postfix policy delegation documentation for more information.

As an example of the class’s utility, and using the above definition of payload, consider:

from chapps.util import PostfixPolicyRequest

ppr = PostfixPolicyRequest(payload)

# all the following are true:
ppr.sender == ''
ppr.sasl_username == ''
ppr.client_address == ''

# demonstrating the pseudo-attribute:
ppr.recipients == ['bar@foo.tld']

Instance attributes (apart from Postfix payload parameters):


the Postfix policy delegation request payload in string-per-line format


a pseudo-attribute of the policy request derived from the value of recipient, provided by Postfix, which may contain more than one comma-separated email address. For reasons unknown, Postfix always provides a recipient_count of 0 before the DATA phase, so we rely upon counting the email addresses directly.


memoization attribute for recipients()


Because the purpose of the class is to present the contents of the initial payload as attributes, all internal attributes are prefaced with an underscore.


Overloaded in order to search for missing attributes in the payload


attr (str) – the attribute which triggered this call


the value found in the payload, or None

Return type


First, if the value of attr starts with an underscore, None is returned. No lines of the payload start with an underscore. This ensures that references to internal attributes of the class are not snarled up with the payload searches.

Next, the payload is searched for the requested key-value pair, attempting to match attr against everything before the = sign. When a line is found, the contents after the = are stored as an attribute named attr (and so memoized), and the value is returned. Future attempts to obtain the value will encounter the attribute and not invoke __getattr__() again.

A DEBUG level message is currently produced if no lines in the payload matched the requested payload data. No errors are produced if a nonexistent attr starting with _ is encountered.

__init__(payload, *args, **kwargs)[source]

Store the payload.


payload (List[str]) – strings which are formatted as ‘key=val’, including an empty entry at the end.

This routine discards the last element of the list and stores the rest as self._payload.

property recipients: List[str]

Memoize recipients as a list


a list of strings which are the email addresses of recipients

Return type


A convenience method to split the ‘recipient’ datum into comma-separated tokens for easier counting.


Given an email address, return the domain part

Raises meaningful errors if nonconforming conditions are encountered.

Return type



email_address (str) –


HELO Whitelisting indicator

Given a mapping of HELO name to expected IP address, indicate whether this PPR represents traffic from a whitelisted server.

Return type



candidates (Dict[str, str]) –