4.7.5.6. Utilities

Utilities and tools.

axonius_api_client.tools.listify(obj, dictkeys=False)[source]

Force an object into a list.

Notes

Parameters
  • obj (typing.Any) – object to coerce to list

  • dictkeys (bool) – if obj is dict, return list of keys of obj

Return type

list

axonius_api_client.tools.grouper(iterable, n, fillvalue=None)[source]

Split an iterable into chunks.

Parameters
Return type

typing.Iterator

axonius_api_client.tools.coerce_int(obj, max_value=None, min_value=None)[source]

Convert an object into int.

Parameters
Raises

ToolsError – if obj is not able to be converted to int

Return type

int

axonius_api_client.tools.coerce_int_float(value)[source]

Convert an object into int or float.

Parameters
Raises

ToolsError – if obj is not able to be converted to int or float

Return type

typing.Union[int, float]

axonius_api_client.tools.coerce_bool(obj, errmsg=None)[source]

Convert an object into bool.

Parameters
Raises

ToolsError – obj is not able to be converted to bool

Return type

bool

axonius_api_client.tools.is_int(obj, digit=False)[source]

Check if obj is int typeable.

Parameters
  • obj (typing.Any) – object to check

  • digit (bool) – allow checking str/bytes

Return type

bool

axonius_api_client.tools.join_url(url, *parts)[source]

Join a URL to any number of parts.

Parameters
  • url (str) – str to add parts to

  • *parts – str(s) to append to url

Return type

str

axonius_api_client.tools.strip_right(obj, fix)[source]

Strip text from the right side of obj.

Parameters
Return type

typing.Union[typing.List[str], str]

axonius_api_client.tools.strip_left(obj, fix)[source]

Strip text from the left side of obj.

Parameters
Return type

typing.Union[typing.List[str], str]

class axonius_api_client.tools.AxJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

Pass.

default(obj)[source]

Pass.

__init__(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
item_separator = ', '
iterencode(o, _one_shot=False)

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
key_separator = ': '
axonius_api_client.tools.json_dump(obj, indent=2, sort_keys=False, error=True, **kwargs)[source]

Serialize an object into json str.

Parameters
  • obj (typing.Any) – object to serialize into json str

  • indent (int) – json str indent level

  • sort_keys (bool) – sort dict keys

  • error (bool) – if json error happens, raise it

  • **kwargs – passed to json.dumps()

Return type

typing.Any

axonius_api_client.tools.json_load(obj, error=True, **kwargs)[source]

Deserialize a json str into an object.

Parameters
  • obj (str) – str to deserialize into obj

  • error (bool) – if json error happens, raise it

  • **kwargs – passed to json.loads()

Return type

typing.Any

axonius_api_client.tools.json_reload(obj, error=False, trim=None, **kwargs)[source]

Re-serialize a json str into a pretty json str.

Parameters
Return type

str

axonius_api_client.tools.dt_parse(obj, default_tz_utc=False)[source]

Parse a str, datetime, or timedelta into a datetime object.

Notes

Parameters
Return type

datetime.datetime

axonius_api_client.tools.dt_parse_tmpl(obj, tmpl='%Y-%m-%d')[source]

Parse a string into the format used by the REST API.

Parameters
Return type

str

axonius_api_client.tools.dt_now(delta=None, tz=tzutc())[source]

Get the current datetime in for a specific tz.

Parameters
Return type

datetime.datetime

axonius_api_client.tools.dt_sec_ago(obj, exact=False)[source]

Get number of seconds ago a given datetime was.

Parameters
Return type

int

axonius_api_client.tools.dt_min_ago(obj)[source]

Get number of minutes ago a given datetime was.

Parameters

obj (typing.Union[str, datetime.timedelta, datetime.datetime]) – parsed by dt_sec_ago() into seconds ago

Return type

int

axonius_api_client.tools.dt_days_left(obj)[source]

Get number of days left until a given datetime.

Parameters

obj (typing.Union[str, datetime.timedelta, datetime.datetime, None]) – parsed by dt_sec_ago() into days left

Return type

typing.Optional[int]

axonius_api_client.tools.dt_within_min(obj, n=None)[source]

Check if given datetime is within the past n minutes.

Parameters
Return type

bool

axonius_api_client.tools.get_path(obj)[source]

Convert a str into a fully resolved & expanded Path object.

Parameters

obj (typing.Union[str, pathlib.Path]) – obj to convert into expanded and resolved absolute Path obj

Return type

pathlib.Path

axonius_api_client.tools.path_read(obj, binary=False, is_json=False, **kwargs)[source]

Read data from a file.

Notes

  • if path filename ends with “.json”, data will be deserialized using json_load()

Parameters
Raises

ToolsError – path does not exist as file

Return type

typing.Union[bytes, str]

axonius_api_client.tools.path_write(obj, data, overwrite=False, binary=False, binary_encoding='utf-8', is_json=False, make_parent=True, protect_file=384, protect_parent=448, **kwargs)[source]

Write data to a file.

Notes

  • if obj filename ends with “.json”, serializes data using json_dump().

Parameters
  • obj (typing.Union[str, pathlib.Path]) – path to write data to, parsed by get_path()

  • data (typing.Union[bytes, str]) – data to write to obj

  • binary (bool) – write the data as binary instead of str

  • binary_encoding (str) – encoding to use when switching from str/bytes

  • is_json (bool) – serialize data using json_load()

  • overwrite (bool) – overwrite obj if exists

  • make_parent (bool) – If the parent directory does not exist, create it

  • protect_file – octal mode of permissions to set on file

  • protect_dir – octal mode of permissions to set on parent directory when creating

  • **kwargs – passed to json_dump()

Raises
  • ToolsError – path exists as file and overwrite is False

  • ToolsError – if parent path does not exist and make_parent is False

Return type

typing.Tuple[pathlib.Path, typing.Callable]

axonius_api_client.tools.longest_str(obj)[source]

Determine the length of the longest string in a list of strings.

Parameters

obj (typing.List[str]) – list of strings to calculate length of

Return type

int

axonius_api_client.tools.split_str(obj, split=',', strip=None, do_strip=True, lower=True, empty=False)[source]

Split a string or list of strings into a list of strings.

Parameters
  • obj (typing.Union[typing.List[str], str]) – string or list of strings to split

  • split (str) – character to split on

  • strip (typing.Optional[str]) – characters to strip

  • do_strip (bool) – strip each item from the split

  • lower (bool) – lowercase each item from the split

  • empty (bool) – remove empty items post split

Return type

typing.List[str]

axonius_api_client.tools.echo_ok(msg, tmpl=True, **kwargs)[source]

Echo a message to console.

Parameters
  • msg (str) – message to echo

  • tmpl (bool) – template to using for echo

  • kwargs – passed to click.secho

axonius_api_client.tools.echo_warn(msg, tmpl=True, **kwargs)[source]

Echo a warning message to console.

Parameters
  • msg (str) – message to echo

  • tmpl (bool) – template to using for echo

  • kwargs – passed to click.secho

axonius_api_client.tools.echo_error(msg, abort=True, tmpl=True, **kwargs)[source]

Echo an error message to console.

Parameters
  • msg (str) – message to echo

  • tmpl (bool) – template to using for echo

  • kwargs – passed to click.secho

  • abort (bool) – call sys.exit(1) after echoing message

axonius_api_client.tools.sysinfo()[source]

Gather system information.

Return type

dict

axonius_api_client.tools.calc_percent(part, whole, places=2)[source]

Calculate the percentage of part out of whole.

Parameters
Return type

float

axonius_api_client.tools.trim_float(value, places=2)[source]

Trim a float to N places.

Parameters
  • value (float) – float to trim

  • places (int) – decimal places to trim value to

Return type

float

axonius_api_client.tools.join_kv(obj, listjoin=', ', tmpl='{k}: {v!r}')[source]

Join a dictionary into key value strings.

Parameters
  • obj (typing.Union[typing.List[dict], dict]) – dict or list of dicts to stringify

  • listjoin (str) – string to use for joining

  • tmpl (str) – template to format key value pairs of dict

Return type

typing.List[str]

axonius_api_client.tools.get_type_str(obj)[source]

Get the type name of a class.

Parameters

obj (typing.Any) – class or tuple of classes to get type name(s) of

axonius_api_client.tools.check_type(value, exp, name='', exp_items=None)[source]

Check that a value is the appropriate type.

Parameters
  • value (typing.Any) – value to check type of

  • exp (typing.Any) – type(s) that value should be

  • name (str) – identifier of what value is for

  • exp_items (typing.Optional[typing.Any]) – if value is a list, type(s) that list items should be

axonius_api_client.tools.check_empty(value, name='')[source]

Check if a value is empty.

Parameters
  • value (typing.Any) – value to check type of

  • name (str) – identifier of what value is for

axonius_api_client.tools.get_raw_version(value)[source]

Caclulate the raw bits of a version str.

Parameters

value (str) – version to calculate

Return type

str

axonius_api_client.tools.coerce_str_to_csv(value)[source]

Coerce a string into a list of strings.

Parameters

value (str) – string to seperate using comma

Return type

typing.List[str]

axonius_api_client.tools.parse_ip_address(value)[source]

Parse a string into an IP address.

Parameters

value (str) – ip address

Return type

typing.Union[ipaddress.IPv4Address, ipaddress.IPv6Address]

axonius_api_client.tools.parse_ip_network(value)[source]

Parse a string into an IP network.

Parameters

value (str) – ip network

Return type

typing.Union[ipaddress.IPv4Network, ipaddress.IPv6Network]

axonius_api_client.tools.kv_dump(obj)[source]

Get a string representation of a dictionaries key value pairs.

Parameters

obj (dict) – dictionary to get string of

Return type

str

axonius_api_client.tools.bom_strip(content, strip=True)[source]

Remove the UTF-8 BOM marker from the beginning of a string.

Parameters
  • content (str) – string to remove BOM marker from if found

  • strip – remove whitespace before & after removing BOM marker

Return type

str

axonius_api_client.tools.read_stream(stream)[source]

Try to read input from a stream.

Parameters

stream – stdin or a file descriptor to read input from

Return type

str

axonius_api_client.tools.check_gui_page_size(size=None)[source]

Check page size to see if it one of the valid GUI page sizes.

Parameters

size (typing.Optional[int]) – page size to check

Raises

ApiError – if size is not one of axonius_api_client.constants.api.GUI_PAGE_SIZES

Return type

int

axonius_api_client.tools.calc_gb(value, places=2, is_kb=True)[source]

Convert bytes into GB.

Parameters
  • value (typing.Union[str, int]) – bytes

  • places (int) – decimal places to trim value to

  • is_kb (bool) – values are in kb or bytes

Return type

float

axonius_api_client.tools.calc_perc_gb(obj, whole_key, part_key, perc_key=None, places=2, update=True, is_kb=True)[source]

Calculate the GB and percent from a dict.

Parameters
  • obj (dict) – dict to get whole_key and part_key from

  • whole_key (str) – key to get whole value from and convert to GB and set as whole_key_gb

  • part_key (str) – key to get part value from and convert to GB and set as part_key_gb

  • perc_key (typing.Optional[str]) – key to set percent in

  • is_kb (bool) – values are in kb or bytes

  • places (int) –

  • update (bool) –

Return type

dict

axonius_api_client.tools.get_subcls(cls)[source]

Get all subclasses of a class.

Return type

list

axonius_api_client.tools.prettify_obj(obj, indent=0)[source]

Pass.

axonius_api_client.tools.token_parse(obj)[source]

Pass.

Parameters

obj (str) –

Return type

str

axonius_api_client.tools.combo_dicts(*args)[source]

Pass.

axonius_api_client.tools.is_url(value)[source]

Pass.

Parameters

value (str) –

Return type

bool