aea.helpers.base
Miscellaneous helpers.
locate
Locate an object by name or dotted save_path, importing as necessary.
load_
module
Load a module.
Arguments:
dotted_path
: the dotted save_path of the package/module.filepath
: the file to the package/module.
Returns:
module type
Raises:
ValueError
: if the filepath provided is not a module. # noqa: DAR402Exception
: if the execution of the module raises exception. # noqa: DAR402
load_
env_
file
Load the content of the environment file into the process environment.
Arguments:
env_file
: save_path to the env file.
sigint_
crossplatform
Send a SIGINT, cross-platform.
The reason is because the subprocess module doesn't have an API to send a SIGINT-like signal both on Posix and Windows with a single method.
However, a subprocess.Popen class has the method 'send_signal' that gives more flexibility in this terms.
Arguments:
process
: the process to send the signal to.
win_
popen_
kwargs
Return kwargs to start a process in windows with new process group.
Help to handle ctrl c properly. Return empty dict if platform is not win32
Returns:
windows popen kwargs
send_
control_
c
Send ctrl-C cross-platform to terminate a subprocess.
Arguments:
process
: the process to send the signal to.kill_group
: whether or not to kill group
RegexConstrainedString Objects
A string that is constrained by a regex.
The default behaviour is to match anything. Subclass this class and change the 'REGEX' class attribute to implement a different behaviour.
__
init__
Initialize a regex constrained string.
SimpleId Objects
A simple identifier.
The allowed strings are all the strings that: - have at least length 1 - have at most length 128 - the first character must be between a-z,A-Z or underscore - the other characters must be either the above or digits.
Examples of allowed strings:
SimpleId("an_identifier") 'an_identifier'
Examples of not allowed strings:
SimpleId("0an_identifier") Traceback (most recent call last): ... ValueError: Value 0an_identifier does not match the regular expression re.compile('[a-zA-Z_][a-zA-Z0-9_]{0,127}')
SimpleId("an identifier") Traceback (most recent call last): ... ValueError: Value an identifier does not match the regular expression re.compile('[a-zA-Z_][a-zA-Z0-9_]{0,127}')
SimpleId("") Traceback (most recent call last): ... ValueError: Value does not match the regular expression re.compile('[a-zA-Z_][a-zA-Z0-9_]{0,127}')
cd
Change working directory temporarily.
get_
logger_
method
Get logger method for function.
Get logger in fn
definition module or creates logger is module.name.
Or return logger_method if it's callable.
Arguments:
fn
: function to get logger for.logger_method
: logger name or callable.
Returns:
callable to write log with
try_
decorator
try_decorator(error_message: str, default_return: Callable = None, logger_method: Any = "error") -> Callable
Run function, log and return default value on exception.
Does not support async or coroutines!
Arguments:
error_message
: message template with one{}
for exceptiondefault_return
: value to return on exception, by default Nonelogger_method
: name of the logger method or callable to print logs
Returns:
the callable
MaxRetriesError Objects
Exception for retry decorator.
retry_
decorator
retry_decorator(number_of_retries: int, error_message: str, delay: float = 0, logger_method: str = "error") -> Callable
Run function with several attempts.
Does not support async or coroutines!
Arguments:
number_of_retries
: amount of attemptserror_message
: message template with one{}
for exceptiondelay
: number of seconds to sleep between retries. default 0logger_method
: name of the logger method or callable to print logs
Returns:
the callable
exception_
log_
and_
reraise
@contextlib.contextmanager
exception_log_and_reraise(log_method: Callable, message: str) -> Generator
Run code in context to log and re raise exception.
Arguments:
log_method
: function to print logmessage
: message template to add error text. :yield: the generator
recursive_
update
Update a dictionary by replacing conflicts with the new values.
It does side-effects to the first dictionary.
to_update = dict(a=1, b=2, subdict=dict(subfield1=1)) new_values = dict(b=3, subdict=dict(subfield1=2)) recursive_update(to_update, new_values) to_update {'a': 1, 'b': 3, 'subdict': {'subfield1': 2}}
Arguments:
to_update
: the dictionary to update.new_values
: the dictionary of new values to replace.allow_new_values
: whether or not to allow new values.
find_
topological_
order
Compute the topological order of a graph (using Kahn's algorithm).
Arguments:
adjacency_list
: the adjacency list of the graph.
Returns:
the topological order for the graph (as a sequence of nodes)
Raises:
ValueError
: if the graph contains a cycle.
reachable_
nodes
Find the reachable subgraph induced by a set of starting nodes.
Arguments:
adjacency_list
: the adjacency list of the full graph.starting_nodes
: the starting nodes of the new graph.
Returns:
the adjacency list of the subgraph.
cached_
property Objects
Cached property from python3.8 functools.
__
init__
Init cached property.
__
set_
name__
Set name.
__
get__
Get instance.
ensure_
dir
Check if dir_path is a directory or create it.
dict_
to_
path_
value
Convert dict to sequence of terminal path build of keys and value.
parse_
datetime_
from_
str
Parse datetime from string.
CertRequest Objects
Certificate request for proof of representation.
__
init__
| __init__(public_key: str, identifier: SimpleIdOrStr, ledger_id: SimpleIdOrStr, not_before: str, not_after: str, message_format: str, save_path: str) -> None
Initialize the certificate request.
Arguments:
public_key
: the public key, or the key id.identifier
: certificate identifier.ledger_id
: ledger identifier the request is referring to.not_before
: specify the lower bound for certificate validity. If it is a string, it must follow the format: 'YYYY-MM-DD'. It will be interpreted as timezone UTC-0.not_after
: specify the lower bound for certificate validity. If it is a string, it must follow the format: 'YYYY-MM-DD'. It will be interpreted as timezone UTC-0.message_format
: message format used for signingsave_path
: the save_path where to save the certificate.
public_
key
Get the public key.
ledger_
id
Get the ledger id.
key_
identifier
Get the key identifier.
identifier
Get the identifier.
not_
before_
string
Get the not_before field as string.
not_
after_
string
Get the not_after field as string.
not_
before
Get the not_before field.
not_
after
Get the not_after field.
message_
format
Get the message format.
save_
path
Get the save path for the certificate.
Note: if the path is not absolute, then the actual save path might depend on the context.
Returns:
the save path
get_
absolute_
save_
path
Get the absolute save path.
If save_path is an absolute path, then the prefix is ignored. Otherwise, the path prefix is prepended.
Arguments:
path_prefix
: the (absolute) path to prepend to the save path.
Returns:
the actual save path.
public_
key_
or_
identifier
Get the public key or identifier.
get_
message
Get the message to sign.
construct_
message
| @classmethod
| construct_message(cls, public_key: str, identifier: SimpleIdOrStr, not_before_string: str, not_after_string: str, message_format: str) -> bytes
Construct message for singning.
Arguments:
public_key
: the public keyidentifier
: identifier to be signednot_before_string
: signature not valid beforenot_after_string
: signature not valid aftermessage_format
: message format used for signing
Returns:
the message
get_
signature
Get signature from save_path.
Arguments:
path_prefix
: the path prefix to be prepended to save_path. Defaults to cwd.
Returns:
the signature.
json
Compute the JSON representation.
from_
json
Compute the JSON representation.
__
eq__
Check equality.
compute_
specifier_
from_
version
Compute the specifier set from a version.
version specifier is: >=major.minor.0, <next_major.0.0
Arguments:
version
: the version
Returns:
the specifier set
decorator_
with_
optional_
params
Make a decorator usable either with or without parameters.
In other words, if a decorator "mydecorator" is decorated with this decorator, It can be used both as:
@mydecorator def myfunction(): ...
or as:
@mydecorator(arg1, kwarg1="value") def myfunction(): ...
Arguments:
decorator
: a decorator callable
Returns:
a decorator callable
delete_
directory_
contents
Delete the content of a directory, without deleting it.
prepend_
if_
not_
absolute
Prepend a path with a prefix, but only if not absolute
Arguments:
path
: the path to process.prefix
: the path prefix.
Returns:
the same path if absolute, else the prepended path.