mstrio.utils package

Subpackages

Submodules

mstrio.utils.acl module

class mstrio.utils.acl.ACE(deny: bool, entry_type: int, rights: mstrio.utils.acl.Rights | int, trustee_id: str, trustee_name: str, trustee_type: int, trustee_subtype: int, inheritable: bool)

Bases: Dictable

classmethod from_dict(source: dict[str, Any], connection: Connection)

Creates an object from a dictionary. The dictionary’s keys in camel case are changed to object’s attribute names (by default in snake case) and dict values are composed to their proper data types such as Enums, list of Enums etc. as specified in _FROM_DICT_MAP.

Parameters:
  • cls (T) – Class (type) of an object that should be created.

  • source (Dict[str, Any]) – A dictionary from which an object will be constructed.

  • connection (Connection, optional) – A MSTR Connection object. Defaults to None.

  • to_snake_case (bool, optional) – Set to True if attribute names should be converted from camel case to snake case. Defaults to True.

Returns:

An object of type T.

Return type:

T

to_dict(camel_case=True)

Converts an object to a dictionary excluding object’s private properties. When converting the object to a dictionary, the object’s attributes become the dictionary’s keys and are in camel case by default Attribute values stored as objects are automatically converted to non-/ primitive data structures.

Parameters:

camel_case (bool, optional) – Set to True if attribute names should be converted from snake case to camel case. Defaults to True.

Returns:

A dictionary representation of object’s attributes and values.

By default, the dictionary keys are in camel case.

Return type:

dict

class mstrio.utils.acl.ACLMixin

Bases: object

ACLMixin class adds Access Control List (ACL) management for supporting objects.

An ACL is a set of permissions on objects so that users or user groups have control over individual objects in the system. Those permissions decide whether or not a user can perform a particular class of operations on a particular object. For example, a user may have permissions to view and execute a report , but cannot modify the report definition or delete the report.

NOTE: Must be mixedin with Entity or its subclasses.

acl_add(rights: int | mstrio.utils.acl.Rights | mstrio.utils.acl.AggregatedRights, trustees: list[UserOrGroup] | UserOrGroup, denied: bool = False, inheritable: Optional[bool] = None, propagate_to_children: Optional[bool] = None) None

Add Access Control Element (ACE) to the object ACL.

Note

Argument propagate_to_children is used only for objects with type ObjectTypes.FOLDER.

Parameters:
  • rights – The degree to which the user or group is granted or denied access to the object. The available permissions are defined in Rights and AggregatedRights Enums

  • trustees – list of trustees (User or UserGroup objects or ids) to update the ACE for

  • denied – flag to indicate granted or denied access to the object

  • inheritable – Applies only to folders. If set, any objects placed in the folder inherit the folder’s entry in the ACL.

  • propagate_to_children – used for folder objects only, default value is None, if set to True/False adds propagateACLToChildren keyword to the request body and sets its value accordingly

Examples

>>> obj.acl_add(rights=Rights.BROWSE | Rights.EXECUTE,
>>>             trustees=user_obj, denied=True)
acl_alter(rights: int | mstrio.utils.acl.Rights | mstrio.utils.acl.AggregatedRights, trustees: list[UserOrGroup] | UserOrGroup, denied: bool = False, inheritable: Optional[bool] = None, propagate_to_children: Optional[bool] = None) None

Alter an existing Access Control Element (ACE) of the object ACL.

Note

Argument propagate_to_children is used only for objects with type ObjectTypes.FOLDER.

Parameters:
  • rights – The degree to which the user or group is granted or denied access to the object. The available permissions are defined in Rights and AggregatedRights Enums

  • trustees – list of trustees (User or UserGroup objects or ids) to update the ACE for

  • denied – flag to indicate granted or denied access to the object

  • inheritable – Applies only to folders. If set, any objects placed in the folder inherit the folder’s entry in the ACL.

  • propagate_to_children – used for folder objects only, default value is None, if set to True/False adds propagateACLToChildren keyword to the request body and sets its value accordingly

Examples

>>> obj.acl_alter(rights=Rights.BROWSE | Rights.EXECUTE,
>>>               trustees=user_obj, denied=True)
acl_remove(rights: int | mstrio.utils.acl.Rights | mstrio.utils.acl.AggregatedRights, trustees: list[UserOrGroup] | UserOrGroup, denied: bool = False, inheritable: Optional[bool] = None, propagate_to_children: Optional[bool] = None) None

Remove Access Control Element (ACE) from the object ACL.

Note

Argument propagate_to_children is used only for objects with type ObjectTypes.FOLDER.

Parameters:
  • rights – The degree to which the user or group is granted or denied access to the object. The available permissions are defined in Rights and AggregatedRights Enums

  • trustees – list of trustees (User or UserGroup objects or ids) to update the ACE for

  • denied – flag to indicate granted or denied access to the object

  • inheritable – Applies only to folders. If set, any objects placed in the folder inherit the folder’s entry in the ACL.

  • propagate_to_children – used for folder objects only, default value is None, if set to True/False adds propagateACLToChildren keyword to the request body and sets its value accordingly

Examples

>>> obj.acl_remove(rights=Rights.BROWSE | Rights.EXECUTE,
>>>                trustees=user_obj, denied=True)
list_acl(to_dataframe: bool = False, to_dictionary: bool = False, **filters) pandas.core.frame.DataFrame | list[dict | mstrio.utils.acl.ACE]

Get Access Control List (ACL) for this object. Optionally filter ACLs by specifying filters.

Parameters:
  • to_dataframe (bool, optional) – if True, return datasets as pandas DataFrame

  • to_dictionary (bool, optional) – if True, return datasets as dicts

  • **filters – Available filter parameters: [deny, type, rights, trustee_id, trustee_name, trustee_type, trustee_subtype, inheritable]

Examples

>>> list_acl(deny=True, trustee_name="John")
class mstrio.utils.acl.AggregatedRights(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: IntFlag

Enumeration constants used to specify combination of Rights values.

ALL = 255
CONSUME = 69
MODIFY = 221
NONE = 0
VIEW = 197
class mstrio.utils.acl.Permissions(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Enumeration constants used to specify combination of Rights values similar to workstation Security Access.

TODO: This has to be string-based to discern between ‘Denied All’ and ‘Full Control’, which have the same mask.

CONSUME = 'Consume'
DEFAULT_ALL = 'Default All'
DENIED_ALL = 'Denied All'
FULL_CONTROL = 'Full Control'
MODIFY = 'Modify'
VIEW = 'View'
class mstrio.utils.acl.Rights(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: IntFlag

“Enumeration constants used to specify the access granted attribute of the DSS objects.

BROWSE = 1
CONTROL = 32
DELETE = 16
EXECUTE = 128
INHERITABLE = 536870912
READ = 4
USE = 64
USE_EXECUTE = 2
WRITE = 8
class mstrio.utils.acl.TrusteeACLMixin

Bases: object

TrusteeACLMixin class adds ACL management for Trustee classes.

Objects currently supporting this Mixin are: (User and UserGroup).

set_custom_permissions(to_objects: str | list[str], object_type: ObjectTypes | int, project: Optional[Project | str] = None, execute: Optional[str] = None, use: Optional[str] = None, control: Optional[str] = None, delete: Optional[str] = None, write: Optional[str] = None, read: Optional[str] = None, browse: Optional[str] = None) None

Set custom permissions to perform actions on given object(s).

Function is used to set rights of the trustee to perform given actions on the provided objects. Within one execution of the function rights will be set in the same manner for each of the provided objects. None of the rights is necessary, but if provided then only possible values are ‘grant’ (to grant right), ‘deny’ (to deny right), ‘default’ (to reset right) or None which is default value and means that nothing will be changed for this right. All objects to which the rights will be given have to be of the same type which is also provided.

Parameters:
  • to_objects – (str, list(str)): List of object ids on access list to which the permissions will be set

  • object_type (int, ObjectTypes) – Type of objects on access list

  • project (str, Project) – Object or id of Project in which the object is located. If not passed, Project (project_id) selected in Connection object is used.

  • execute (str) – value for right “Execute”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • use (str) – value for right “Use”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • control (str) – value for right “Control”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • delete (str) – value for right “Delete”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • write (str) – value for right “Write”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • read (str) – value for right “Read”. Available are ‘grant’, ‘deny’, ‘default’ or None

  • browse (str) – value for right “Browse. Available are ‘grant’, ‘deny’, ‘default’ or None

Returns:

None

set_permission(permission: mstrio.utils.acl.Permissions | str, to_objects: str | list[str], object_type: ObjectTypes | int, project: Optional[Project | str] = None, propagate_to_children: Optional[bool] = None) None

Set permission to perform actions on given object(s).

Function is used to set permission of the trustee to perform given actions on the provided objects. Within one execution of the function permission will be set in the same manner for each of the provided objects. The only available values of permission are: ‘View’, ‘Modify’, ‘Full Control’, ‘Denied All’, ‘Default All’. Permission is the predefined set of rights. All objects to which the rights will be given have to be of the same type which is also provided.

Parameters:
  • permission – The Permission which defines set of rights. See: Permissions enum

  • to_objects – List of object ids on access list for which the permissions will be set

  • object_type – Type of objects on access list. See: ObjectTypes enum

  • project – Object or id of Project where the object is located. If not passed, Project (project_id) selected in Connection object is used

  • propagate_to_children – Flag used in the request to determine if those rights will be propagated to children of the trustee

Returns:

None

mstrio.utils.acl.modify_rights(connection, object_type: ObjectTypes | int, ids: list[str] | str, op: str, rights: int, trustees: list[UserOrGroup] | UserOrGroup, denied: bool = False, inheritable: Optional[bool] = None, propagate_to_children: Optional[bool] = None, project: Optional[Project | str] = None) None | dict

Updates the ACL for all given objects specified by id from ids list, performs operation defined by the op parameter on all objects for every user or group from trustees list.

Note

Argument inheritable and propagate_to_children are used only for objects with type ObjectTypes.FOLDER.

Parameters:
  • object_type (ObjectTypes, int) – Type of every object from ids list. One of EnumDSSXMLObjectTypes. Ex. 34 (User or UserGroup), 44 (Security Role), 32 (Project), 8 (Folder).

  • ids (list[str], str) – List of object ids or one object id on which operations will be performed.

  • op (str) – ACL update operator, available values are “ADD”, “REMOVE” and “REPLACE”.

  • rights (int) – Value of rights to use by the operator.

  • trustees (list[UserOrGroup], UserOrGroup) – List of trustees or one trustee to update the ACE for.

  • denied (bool) – Flag to indicate granted or denied access to the object.

  • inheritable (bool, optional) – Applies only to folders. If set, any objects placed in the folder inherit the folder’s entry in the ACL.

  • propagate_to_children (bool, optional) – Used for folder objects only, default value is None, if set to True/False adds propagateACLToChildren keyword to the request body and sets its value accordingly.

  • project (Project, str, optional) – Project object or project id on which objects are stored, if not specified project id from connection will be used.

Returns:

Dict with updated object properties if there was only one id in ids list or None.

mstrio.utils.api_helpers module

mstrio.utils.api_helpers.async_get(async_wrapper: callable, connection: Connection, ids: List[str], error_msg: Optional[str] = None, **kwargs) List[dict]

Asynchronously get results of single object GET requests. GET requests requires to have future session param to be used with this function. Threads number is set automatically.

Parameters:
  • async_wrapper – callable async REST API wrapper function

  • connection – Connection object

  • ids – list of objects ids to be retrieved

  • error_msg – optional error message

  • kwargs – additional async wrapper arguments to be passed

Returns:

List of responses as a list of dicts

Examples

>>> async_get(tables.get_table_async, connection, ['112233','223344'])
mstrio.utils.api_helpers.changeset_manager(connection)
mstrio.utils.api_helpers.unpack_information(func)
mstrio.utils.api_helpers.unpack_table(response_json)
mstrio.utils.api_helpers.unpack_tables(response_json)

mstrio.utils.cache module

class mstrio.utils.cache.Cache(connection: Connection, cache_id: str, cache_dict: Optional[dict] = None)

Bases: object

Base class for managing cache.

list_properties()

List properties for cache.

class mstrio.utils.cache.CacheSource(id: str, name: str, type: mstrio.utils.cache.CacheSource.Type)

Bases: Dictable

class Type(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: AutoName

CUBE = 'cube'
DOCDOSSIER = 'docdossier'
DOCUMENT = 'document'
DOSSIER = 'dossier'
REPORT = 'report'
id: str
name: str
type: Type
class mstrio.utils.cache.ContentCacheMixin

Bases: object

ContentCacheMixin class adds ContentCache management for supporting cache

Objects currently supported are ContentCache for documents, dossiers and reports.

classmethod delete_all_caches(connection: Connection, force: Optional[bool] = None, **filters)

Delete all content caches filtered by the class type. Optionally filter by additional conditions.

Parameters:
  • cls (object) – Class type for objects to be filtered by

  • connection (Connection) – MicroStrategy connection object returned by connection.Connection()

  • force (bool, optional) – If True, then no additional prompt will be shown before deleting objects.

  • **filters – Available filter parameters: [‘db_connection_id’, ‘db_login_id’, ‘owner’, ‘status’, ‘size’, ‘wh_tables’, ‘security_filter_id’]

static delete_caches(connection: Connection, cache_ids: list[str], force: Optional[bool] = None) Response

Bulk delete caches.

Parameters:
  • connection (Connection) – MicroStrategy connection object returned

  • 'connection.Connection()' (by) –

  • cache_ids (list[str]) – list of cache ids to be deleted

  • force (bool, optional) – If True, then no additional prompt will be shown before deleting objects.

Returns:

Response object.

static fetch_nodes(connection: Connection, project_id: str) list[str]

Fetches the nodes for the specified connection and project.

Parameters:
  • connection (Connection) – MicroStrategy connection object returned by ‘connection.Connection()’

  • project_id (string) – id of the project to fetch the nodes from

Returns:

A list of node names for the specified project.

classmethod list_caches(connection: Connection, to_dictionary: bool = False, status: str = 'ready', project_id: Optional[str] = None, nodes: Optional[Union[list[str], str]] = None, content_type: Optional[Union[Type, str]] = None, limit: Optional[int] = None, db_connection_id: Optional[str] = None, db_login_id: Optional[str] = None, id: Optional[str] = None, owner: Optional[str] = None, size: Optional[str] = None, wh_tables: Optional[str] = None, security_filter_id: Optional[str] = None) list['ContentCache'] | list[dict]

List content caches. You can filter them by id, database connection (db_connection_id) and project (project_id).

You can specify from which nodes caches will be retrieved. If nodes are None then all nodes are retrieved from the cluster.

Parameters:
  • connection (Connection) – MicroStrategy connection object returned by connection.Connection().

  • to_dictionary (bool, optional) – If True returns dict, by default (False) returns ContentCache objects

  • status (string, optional) – When provided, only caches with given status will be returned (if any). Default value ready

  • project_id (string, optional) – When provided only caches for project with given ID will be returned (if any).

  • nodes (list[string] | string, optional) – names of nodes on which caches will be searched. By default, it equals None and in that case all nodes names are loaded from the cluster.

  • content_type (string | CacheSource.Type, optional) – When provided, only caches of given type will be returned (if any).

  • limit (integer, optional) – Cut-off value for the number of objects returned. Default value is 1000 which is a maximum value.

  • db_connection_id (string, optional) – When provided, only caches for the database connection with given ID will be returned (if any).

  • db_login_id (string, optional) – When provided, only caches for the database login with given ID will be returned (if any).

  • id (string, optional) – When provided, only cache with given ID will be returned (if any).

  • owner (string, optional) – Owner of the content cache. Exact match on the owner’s full name.

  • size (string, optional) – Size condition for the content cache (in KB). When provided, only caches which satisfy the condition will be returned (if any).

  • wh_tables (string, optional) – When provided, only caches using given warehouse tables will be returned (if any).

  • security_filter_id (string, optional) – When provided, only caches using given security filter will be returned (if any).

Returns:

List of ContentCache objects when parameter to_dictionary is set to False (default value) or list of dictionaries otherwise.

classmethod load_all_caches(connection: Connection, **filters)

Load all content caches filtered by the class type. Optionally filter by additional conditions.

Parameters:
  • cls (object) – Class type for objects to be filtered by

  • connection (Connection) – MicroStrategy connection object returned by connection.Connection()

  • **filters – Available filter parameters: [‘db_connection_id’, ‘db_login_id’, ‘owner’, ‘status’, ‘size’, ‘wh_tables’, ‘security_filter_id’]

static load_caches(connection: Connection, cache_ids: list[str]) Response

Bulk load caches.

Parameters:
  • connection (Connection) – MicroStrategy connection object returned

  • 'connection.Connection()' (by) –

  • cache_ids (list[str]) – list of cache ids to be loaded

Returns:

Response object.

classmethod unload_all_caches(connection: Connection, **filters)

Unload all content caches filtered by the class type. Optionally filter by additional conditions.

Parameters:
  • cls (object) – Class type for objects to be filtered by

  • connection (Connection) – MicroStrategy connection object returned by connection.Connection()

  • **filters – Available filter parameters: [‘db_connection_id’, ‘db_login_id’, ‘owner’, ‘status’, ‘size’, ‘wh_tables’, ‘security_filter_id’]

static unload_caches(connection: Connection, cache_ids: list[str]) Response

Bulk unload caches.

Parameters:
  • connection (Connection) – MicroStrategy connection object returned

  • 'connection.Connection()' (by) –

  • cache_ids (list[str]) – list of cache ids to be unloaded

Returns:

Response object.

mstrio.utils.certified_info module

class mstrio.utils.certified_info.CertifiedInfo(connection: Connection, certified: bool, date_certified: Optional[str] = None, certifier: Optional[dict] = None)

Bases: Dictable

Certification status, time of certification and information about the certifier (currently only for document and report).

connection

MicroStrategy connection object returned by connection.Connection().

certified

Specifies whether the object is trusted, as determined by the standards set by the certifier

date_certified

time when the object was certified, “yyyy-MM-dd HH:mm:ss” in UTC

certifier

information about the entity certifying the object, User object

mstrio.utils.datasources module

mstrio.utils.datasources.alter_conn_json(response_json)
mstrio.utils.datasources.alter_conn_list_resp(response)
mstrio.utils.datasources.alter_conn_resp(response)
mstrio.utils.datasources.alter_instance_json(response_json)
mstrio.utils.datasources.alter_instance_list_resp(response)
mstrio.utils.datasources.alter_instance_resp(response)
mstrio.utils.datasources.alter_patch_req_body(op_dict, initial_path, altered_path)
mstrio.utils.datasources.get_objects_id(obj, obj_class)

mstrio.utils.dependence_mixin module

class mstrio.utils.dependence_mixin.DependenceMixin

Bases: object

DependenceMixin class adds functionality of listing dependents and dependencies. Must be mixedin with Entity or its subclasses.

list_dependencies(project: Optional[Union[Project, str]] = None, name: Optional[str] = None, pattern: Union[SearchPattern, int] = 4, domain: Union[SearchDomain, int] = 2, object_types: Optional[TypeOrSubtype] = None, used_by_recursive: bool = False, root: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, results_format: Union[SearchResultsFormat, str] = 'LIST', to_dictionary: bool = True, **filters)

List list_dependencies of an object.

Parameters:
  • project (string) – Project object or ID

  • name (string) – Value the search pattern is set to, which will be applied to the names of object types being searched. For example, search for all report objects (type) whose name begins with (patter) B (name).

  • pattern (integer or enum class object) – Pattern to search for, such as Begin With or Exactly. Possible values are available in ENUM mstrio.object_management.SearchPattern. Default value is CONTAINS (4).

  • domain (integer or enum class object) – Domain where the search will be performed, such as Local or Project. Possible values are available in ENUM mstrio.object_management.SearchDomain. Default value is PROJECT (2).

  • root (string, optional) – Folder ID of the root folder where the search will be performed.

  • class (object_types(enum class object or integer or list of enum) – objects or integers): Type(s) of object(s) to be searched, such as Folder, Attribute or User. Possible values available in ENUMs mstrio.types.ObjectTypes and mstrio.types.ObjectSubTypes

  • used_by_recursive (boolean, optional) – Control the Intelligence server to also find objects that are used by the given objects indirectly. Default value is false.

  • results_format (SearchResultsFormat) – either a list or a tree format

  • to_dictionary (bool) – If False returns objects, by default (True) returns dictionaries.

  • limit (int) – limit the number of elements returned. If None (default), all objects are returned.

  • offset (int) – Starting point within the collection of returned results. Used to control paging behavior. Default is 0.

  • **filters – Available filter parameters: [‘id’, ‘name’, ‘description’ ,’date_created’, ‘date_modified’, ‘acg’]

Returns:

list of objects or list of dictionaries

list_dependents(project: Optional[Union[Project, str]] = None, name: Optional[str] = None, pattern: Union[SearchPattern, int] = 4, domain: Union[SearchDomain, int] = 2, object_types: Optional[TypeOrSubtype] = None, uses_recursive: bool = False, root: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, results_format: Union[SearchResultsFormat, str] = 'LIST', to_dictionary: bool = True, **filters)

List dependents of an object.

Parameters:
  • project (string) – Project object or ID

  • name (string) – Value the search pattern is set to, which will be applied to the names of object types being searched. For example, search for all report objects (type) whose name begins with (patter) B (name).

  • pattern (integer or enum class object) – Pattern to search for, such as Begin With or Exactly. Possible values are available in ENUM mstrio.object_management.SearchPattern. Default value is CONTAINS (4).

  • domain (integer or enum class object) – Domain where the search will be performed, such as Local or Project. Possible values are available in ENUM mstrio.object_management.SearchDomain. Default value is PROJECT (2).

  • root (string, optional) – Folder ID of the root folder where the search will be performed.

  • class (object_types(enum class object or integer or list of enum) – objects or integers): Type(s) of object(s) to be searched, such as Folder, Attribute or User. Possible values available in ENUMs mstrio.types.ObjectTypes and mstrio.types.ObjectSubTypes

  • uses_recursive (boolean) – Control the Intelligence server to also find objects that use the given objects indirectly. Default value is false.

  • results_format (SearchResultsFormat) – either a list or a tree format

  • to_dictionary (bool) – If False returns objects, by default (True) returns dictionaries.

  • limit (int) – limit the number of elements returned. If None (default), all objects are returned.

  • offset (int) – Starting point within the collection of returned results. Used to control paging behavior. Default is 0.

  • **filters – Available filter parameters: [‘id’, ‘name’, ‘description’ ,’date_created’, ‘date_modified’, ‘acg’]

Returns:

list of objects or list of dictionaries

mstrio.utils.dict_filter module

mstrio.utils.dict_filter.check_valid_param(dict_object: Dict[KT, VT], params: Iterable) None

Check if filter parameters can be used with given dict.

mstrio.utils.dict_filter.filter_list_of_dicts(list_of_dicts: List[Dict[KT, VT]], **filters: Dict[str, Union[list, str, dict, int, float, bool, Enum]]) List[Dict[KT, VT]]

Filter a list of dicts by providing one or more key-value pair filters.

Parameters:
  • list_of_dicts – list of dicts that will be filtered

  • **kwargs – Supports filtering by list, str, dict, int, float, bool, EntityBase, Enum as filter value. Support simple logical operators like: ‘<,>,<=,>=,!’ if value is str.

Examples

>>>filter_list_of_dicts(l, val=[0, 1, 2], val2=”>2”, val3=False) >>>filter_list_of_dicts(l, val=2, val2=”!2”, val3=SomeEnum(1)) >>>filter_list_of_dicts(l, val={“id”:”123”, “name”:”xxx”}) >>>filter_list_of_dicts(l, val=User(conn, id=”123”))

mstrio.utils.dict_filter.make_dict_filter(param: str, op: str, filter_value: Any) Callable

Return a filter function that takes a dictionary object as parameter.

Once evaluated it return bool value indicating if given parameter- expression is True or False. This function can be used in the filter() method.

mstrio.utils.dict_filter.parse_filter_expression(param: str, expression: Union[list, str, dict, int, float, bool, Enum]) tuple

Parse the filter expression only once

mstrio.utils.encoder module

class mstrio.utils.encoder.Encoder(data_frame, dataset_type)

Bases: object

Internal method for converting a Pandas DataFrame to MicroStrategy compliant base64 encoded JSON.

When creating a data set, MicroStrategy APIs require the tabular data to have been transformed first into JSON and then into a base 64 encoded string before it is transmitted to the Intelligence Server via the REST API to create the data set. This class uses Pandas to handle transforming the DataFrame into a JSON representation of the data. For single-table data sets, MicroStrategy APIs require the JSON data to be formatted using the ‘records’ orientation from Pandas. Conversely, multi-table data sets require the JSON data to have a ‘values’ orientation. Based on the data set type, the correct encoding strategy is applied and the data is then encoded.

__b64_data

DataFrame converted into a Base-64 encoded JSON string.

__orientation

For single-table data sets, “single”; for multi-table

data sets, "multi".
__table_type_orient_map

Mapping used when converting DataFrame rows into proper JSON orientation needed for data uploads.

mstrio.utils.entity module

class mstrio.utils.entity.CertifyMixin

Bases: object

CertifyMixin class adds certifying and decertifying functionality. Must be mixedin with Entity or its subclasses.

certify() bool

Certify object. :param success_msg: Custom message displayed on success.

Returns:

True on success, False otherwise.

decertify() bool

Decertify object. :param success_msg: Custom message displayed on success.

Returns:

True on success, False otherwise.

class mstrio.utils.entity.CopyMixin

Bases: object

CopyMixin class adds creating copies of objects functionality.

Currently project objects are not supported. Must be mixedin with Entity or its subclasses.

create_copy(name: Optional[str] = None, folder_id: Optional[str] = None, project: Optional[Union[Project, str]] = None) Any

Create a copy of the object on the I-Server.

Parameters:
  • name – New name of the object. If None, a default name is generated, such as ‘Old Name (1)’

  • folder_id – ID of the destination folder. If None, the object is saved in the same folder as the source object.

  • project – By default, the project selected when creating Connection object. Override project to specify project where the current object exists.

Returns:

New python object holding the copied object.

class mstrio.utils.entity.DeleteMixin

Bases: object

DeleteMixin class adds deleting objects functionality. Must be mixedin with Entity or its subclasses.

delete(force: bool = False) bool

Delete object.

Parameters:

force – If True, then no additional prompt will be shown before deleting object.

Returns:

True on success. False otherwise.

class mstrio.utils.entity.Entity(connection: Connection, object_id: str, **kwargs)

Bases: EntityBase, ACLMixin, DependenceMixin

Base class representation of the MSTR object.

Provides methods to fetch, update, and view the object. To implement this base class all class attributes have to be provided.

connection

A MicroStrategy connection object

id

Object ID

name

Object name

description

Object description

abbreviation

Object abbreviation

type

Object type

subtype

Object subtype

ext_type

Object extended type

date_created

Creation time, DateTime object

date_modified

Last modification time, DateTime object

version

Version ID

owner

Owner ID and name

icon_path

Object icon path

view_media

View media settings

ancestors

List of ancestor folders

certified_info

Certification status, time of certification, and information about the certifier (currently only for document and report)

acg

Access rights (See EnumDSSXMLAccessRightFlags for possible values)

acl

Object access control list

class mstrio.utils.entity.EntityBase(connection: Connection, object_id: str, **kwargs)

Bases: Dictable

This class is for objects that do not have a specified MSTR type.

Class attributes: _OBJECT_TYPE (ObjectTypes): MSTR Object type defined in ObjectTypes _OBJECT_SUBTYPES (list[ObjectSubTypes] | None): MSTR Object subtype defined

in ObjectSubTypes. It contains a list of subtypes, which the class supports. Used in fetch(), to verify whether the retrieved object is supported. None means that subtype won’t be verified.

_REST_ATTR_MAP (Dict[str, str]): A dictionary whose keys are names of

fields of an HTTP response from the server, and values are their respective Python API mappings. This dictionary is mainly used when overriding _init_variables function to convert field names to attribute names before the object’s attributes initialization. For example, if a value of the job_type field should be stored in a ‘type’ attribute, one can specify this dictionary as: {“job_type” : “type”} and override _init_variables method to implement this mapping such as:

```

kwargs = self._rest_to_python(kwargs) self._AVAILABLE_ATTRIBUTES.update({key: type(val) for key, val

in kwargs.items()})

# init logic follows

```

_API_GETTERS (Dict[Union[str, tuple], Callable]): A dictionary whose keys

are either a name of an attribute (as a string) or names of attributes (as a tuple), and values are the REST API wrapper functions used to fetch related data from a server. For example: {‘id’: objects.get_object_info} or {(‘id’, ‘name’, ‘description): objects.get_object_info}

_FROM_DICT_MAP (Dict[str, Callable]): A dictionary whose keys are

attribute’s name and values are the attribute’s type. This mapping is required to determine a proper composite form in which a value will be stored (such as an Enum, list of Enums etc.). Therefore, only attributes with composite and not primitive data types should be included here.

_AVAILABLE_ATTRIBUTES (Dict[str, type]): A dictionary which keys are

object’s attribute names as strings, and which values are types of attributes value. It is used for validating attribute’s type during the process of properties update. This dictionary is created from keyword arguments passed to an object’s constructor.

_API_PATCH (Dict[Tuple[str], Tuple[Union[Callable, str]]]): A dictionary

whose keys are tuples with an object’s attribute names as strings, and values are tuples with two elements: first element is a REST API wrapper function used to update the object’s properties, and the second element is a definition (as a string) how this update should be performed. For example: {(‘name’, ‘description’, ‘abbreviation’):

(objects.update_object, ‘partial_put’)}

_PATCH_PATH_TYPES (Dict[str, type]): A dictionary whose keys are names of

object’s attributes and values are attribute types. Used to validate correctness of a new value during the process of properties update. For example: {‘id’: str, ‘enabled’: bool}

_API_DELETE(Callable): A function which is used to delete an object from the

server. Defaults to staticmethod(objects.delete_object).

Instance attributes:

connection (Connection): A MicroStrategy connection object id (str): Object’s ID type (ObjectTypes): MicroStrategy Object Type name (str): Object’s name _altered_properties (dict): This is a private attribute which is used to

track and validate local changes to the object. It is used whenever an attribute is trying to be set on the object (see __setattr__). It is also used to determine which properties should be updated on a server (see update_properties)

_fetched_attributes (set): This is a private attribute which is used to

track which attributes have been already fetched from the server. The logic of __getattribute__ method is based on information in this set.

subtype (ObjectSubTypes): The enumeration constant used to specify the

object’s sub-type, which reveals more specific information than the object’s type.

ext_type (ExtendedType): A part of an object stored in the metadata.

It is used is to store additional custom information that can be used to achieve new functionality. For example, to display a report as a map and save it as part of the Report object, you can create an extended property for displaying a report as a map and store it on a server in the object’s properties set.

date_created (DatetimeFormats): The object’s creation time. date_modified (DatetimeFormats): The object’s last modification time. version (str): The object’s version ID. Used to compare if two MSTR

objects are identical. If both objects IDs and objects version IDs are the same, MSTR Object Manager determines that objects as ‘Exists Indentically’. Otherwise, if their IDs match but their version IDs mismatch, MSTR Object Manager determines that objects ‘Exists Differently’.

owner (User): The object’s owner information. icon_path (str): A path to a location where the object’s icon is stored. view_media (int): The enumeration constant used to represent the default

mode of a RSD or a dossier, and available modes of a RSD or a dossier.

ancestors (List[Dict]): A list of the object’s ancestor folders. certified_info (CertifiedInfo): The object’s certification status,

time of certification, and information about the certifier (currently only for document and report)

acg (Rights): The enumeration constant used to specify the access

granted attribute of the object.

acl (List[ACE]): A list of permissions on the object so that users, or

user groups have control over individual objects in the system. Those permissions decide whether or not a user can perform a particular class of operations on a particular object. For example, a user may have permissions to view and execute a report , but cannot modify the report definition or delete the report.

hidden (bool): Determines whether the object is hidden on a server. project_id (str): The ID of a project in which the object resides. comments (List[str]): Custom user’s comments related to the object target_info (dict): ?

fetch(attr: Optional[str] = None) None

Fetch the latest object’s state from the I-Server.

Note

This method can overwrite local changes made to the object.

Parameters:
  • attr (Optional[str]) – Attribute name to be fetched. If not specified

  • dictionary. (it will use all getters specified in _API_GETTERS) –

  • None. (Defaults to) –

Raises:

ValueError – If attr cannot be fetched.

classmethod from_dict(source: Dict[str, Any], connection: Connection, to_snake_case: bool = True) T
Overrides Dictable.from_dict() to instantiate an object from

a dictionary without calling any additional getters.

Parameters:
  • cls (T) – Class (type) of an object that should be created.

  • source (Dict[str, Any]) – a dictionary from which an object will be constructed.

  • connection (Connection) – A MicroStrategy Connection object.

  • to_snake_case (bool, optional) – Set to True if attribute names

  • True. (should be converted from camel case to snake case. Defaults to) –

Returns:

An object of type T.

Return type:

T

list_properties() dict

Fetches all attributes from the server and converts all properties of the object to a dictionary.

Returns:

A dictionary which keys are object’s attribute names, and

which values are object’s attribute values.

Return type:

dict

print() None

Pretty Print all properties of the object.

classmethod to_csv(objects: Union[T, List[T]], name: str, path: Optional[str] = None, properties: Optional[List[str]] = None) None

Exports MSTR objects to a csv file.

Optionally, saves only the object properties specified in the properties parameter.

Parameters:
  • objects (Union[T, List[T]]) – List of objects of the same type that

  • exported. (will be) –

  • name (str) – The name of the csv file ending with ‘.csv’

  • path (Optional[str], optional) – A path to the directory where the file will be saved. Defaults to None.

  • properties (Optional[List[str]], optional) – A list of object’s attribute names that should be included in the exported file. Defaults to None.

Raises:
  • TypeError – If objects is not of type T or list of type T

  • objects.

to_dataframe() DataFrame

Converts all properties of the object to a dataframe.

Returns:

A DataFrame object containing object properties.

Return type:

DataFrame

update_properties() None

Save compatible local changes of the object attributes to the I-Server. Changes are retrieved from the self._altered_properties dictionary. After the process of update has finished, self._altered_properties is cleared. For this method to work properly, you must override the _alter_properties() method in a subclass.

Raises:

requests.HTTPError – If I-Server raises exception

class mstrio.utils.entity.MoveMixin

Bases: object

MoveMixin class adds moving objects functionality. Must be mixedin with Entity or its subclasses.

move(folder: Union[Folder, str])

Move the object to a folder on the I-Server.

Parameters:

folder – Destination folder, specified either by id or the Folder object.

class mstrio.utils.entity.VldbMixin

Bases: object

VLDBMixin class adds vldb management for supporting objects.

Objects currently supporting VLDB settings are dataset, document, dossier. Must be mixedin with Entity or its subclasses.

alter_vldb_settings(property_set_name: str, name: str, value: dict, project: Optional[str] = None) None

Alter VLDB settings for a given property set.

list_vldb_settings(project: Optional[str] = None) list

List VLDB settings.

reset_vldb_settings(project: Optional[str] = None) None

Reset VLDB settings to default values.

mstrio.utils.entity.auto_match_args_entity(func: Callable, obj: EntityBase, exclude: list = [], include_defaults: bool = True) dict

Automatically match obj object data to function arguments.

Handles default parameters. Extracts value from Enums. Returns matched arguments as dict.

Parameters:
  • function – function for which args will be matched

  • obj – object to use for matching the function args

  • exclude – set exclude parameter to exclude specific param-value pairs

  • include_defaults – if False then values which have the same value as default will not be included in the result

Raises:

KeyError – could not match all required arguments

mstrio.utils.enum_helper module

class mstrio.utils.enum_helper.AutoName(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

classmethod has_value(value)
class mstrio.utils.enum_helper.AutoUpperName(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

mstrio.utils.enum_helper.get_enum(obj, enum: ~typing.Union[~enum.Enum, ~typing.Tuple[~enum.Enum]] = <enum 'Enum'>) Optional[Enum]

Safely get enum from enum or str.

mstrio.utils.enum_helper.get_enum_val(obj, enum: ~typing.Union[~enum.Enum, ~typing.Tuple[~enum.Enum]] = <enum 'Enum'>) Optional[str]

Safely extract value from enum or str.

mstrio.utils.enum_helper.validate_enum_value(obj, enum)

Validate provided value. If not correct, error message with possible options will be displayed.

mstrio.utils.error_handlers module

class mstrio.utils.error_handlers.ErrorHandler(err_msg: str)

Bases: object

An easy-to-use class decorator designed to replace logic responsible for displaying the error message in API wrappers.

err_msg

error message to be displayed in case of error

Type:

str

Usage:

to replace the code below

if not response.ok:
if error_msg is None:

error_msg = f’Error deleting Datasource Login with ID {id}’

response_handler(response, error_msg)

return response

use the decorator in a following way

@ErrorHandler(err_msg=’Error deleting Datasource Login with ID {id}’) def func(connection, id):

the strings in curly braces will be replaced with the appropriate values if they appear in the function arguments

mstrio.utils.error_handlers.bulk_operation_response_handler(response: Response, unpack_value: str = None) Union[PartialSuccess, Success, MstrException]

Handle partial success and other statuses from bulk operation.

mstrio.utils.error_handlers.get_args_and_bind_values(func: Callable[[Any], Any], *args, **kwargs)

mstrio.utils.exceptions module

exception mstrio.utils.exceptions.NotSupportedError

Bases: Exception

mstrio.utils.filter module

class mstrio.utils.filter.Filter(attributes: list, metrics: list, attr_elements: Optional[list] = None, row_count_metrics: Optional[list] = None, operator: str = 'In')

Bases: object

err_msg_duplicated = "Duplicate object ID: '{}'"
err_msg_invalid = "Invalid object ID: '{}'"

mstrio.utils.formjson module

mstrio.utils.formjson.formjson(df, table_name, as_metrics=None, as_attributes=None)

mstrio.utils.helper module

class mstrio.utils.helper.Dictable

Bases: object

The fundamental class in mstrio-py package. Includes support for converting an object to a dictionary, and creating an object from a dictionary.

classmethod bulk_from_dict(source_list: list[dict[str, Any]], connection: Optional[Connection] = None, to_snake_case: bool = True) list[T]

Creates multiple objects from a list of dictionaries. For each dictionary provided the keys in camel case are changed to object’s attribute names (by default in snake case) and dict values are composed to their proper data types such as Enums, list of Enums etc. as specified in the object’s _FROM_DICT_MAP.

Parameters:
  • cls (T) – Class (type) of the objects that should be created.

  • source_list (List[Dict[str, Any]]) – A list of dictionaries from which the objects will be constructed.

  • connection (Connection, optional) – A MSTR Connection object. Defaults to None.

  • to_snake_case (bool, optional) – Set to True if attribute names should be converted from camel case to snake case. Defaults to True.

Returns:

A list of objects of type T.

Return type:

T

classmethod from_dict(source: Dict[str, Any], connection: Optional[Connection] = None, to_snake_case: bool = True) T

Creates an object from a dictionary. The dictionary’s keys in camel case are changed to object’s attribute names (by default in snake case) and dict values are composed to their proper data types such as Enums, list of Enums etc. as specified in _FROM_DICT_MAP.

Parameters:
  • cls (T) – Class (type) of an object that should be created.

  • source (Dict[str, Any]) – A dictionary from which an object will be constructed.

  • connection (Connection, optional) – A MSTR Connection object. Defaults to None.

  • to_snake_case (bool, optional) – Set to True if attribute names should be converted from camel case to snake case. Defaults to True.

Returns:

An object of type T.

Return type:

T

to_dict(camel_case: bool = True) dict

Converts an object to a dictionary excluding object’s private properties. When converting the object to a dictionary, the object’s attributes become the dictionary’s keys and are in camel case by default Attribute values stored as objects are automatically converted to non-/ primitive data structures.

Parameters:

camel_case (bool, optional) – Set to True if attribute names should be converted from snake case to camel case. Defaults to True.

Returns:

A dictionary representation of object’s attributes and values.

By default, the dictionary keys are in camel case.

Return type:

dict

exception mstrio.utils.helper.IServerError(message, http_code)

Bases: OSError

mstrio.utils.helper.auto_match_args(func: Callable, param_dict: dict, exclude: Optional[list] = None, include_defaults: bool = True) dict

Automatically match dict data to function arguments.

Handles default parameters. Extracts value from Enums. Returns matched arguments as dict.

Note: don’t use it for alter purposes as, changing parameter value

back to default currently doesn’t work (Rework line 413?)

Parameters:
  • function – function for which args will be matched

  • param_dict – dict to use for matching the function args

  • exclude – set exclude parameter to exclude specific param-value pairs

  • include_defaults – if False then values which have the same value as default will not be included in the result

Raises:

KeyError – could not match all required arguments

mstrio.utils.helper.camel_to_snake(response: Union[dict, list], whitelist: list[str] = None) Union[dict, List[dict]]

Converts dictionary keys from camelCase to snake_case. It works recursively for dicts in dicts.

mstrio.utils.helper.check_duplicated_column_names(data_frame)
mstrio.utils.helper.choose_cube(connection: Connection, cube_dict: dict) Optional[Union[OlapCube, SuperCube]]

Return correct cube object based on dictionary with cube’s info.

Note: In case of wrong subtype, None is returned.

mstrio.utils.helper.create_folder(connection, folder_name: str, folder_description: Optional[str] = None, parent_name: Optional[str] = None, parent_id: Optional[str] = None)

Create a folder.

Parameters:
  • connection – MicroStrategy connection object returned by connection.Connection().

  • folder_name (string) – name of the folder which will be created

  • folder_description (string, optional) – description of the folder which will be created

  • parent_name (string, optional) – name of the folder in which new folder will be created

  • parent_id (string, optional) – id of the folder in which new folder will be created

  • error_msg (string, optional) – error message

Returns:

full response about the creation of the folder

Raises:

Exception when

  • neither parent_name nor parent_id is specified - both parent_name and parent_id are specified - parent folder was not found or multiple folders with the same name exists when providing parent_name

mstrio.utils.helper.delete_folder(connection, id: Optional[str] = None, name: Optional[str] = None, error_msg=None)

Delete a folder.

Parameters:
  • connection – MicroStrategy connection object returned by connection.Connection().

  • id (string, optional) – id of the folder which will be deleted

  • name (string, optional) – name of the folder which will be deleted

  • error_msg (string, optional) – error message

Returns:

full response about the deletion of the folder

Raises:

Exception when

  • neither name nor id is specified - both name and id are specified - folder was not found or multiple folders with the same name exists when providing name

mstrio.utils.helper.delete_none_values(source: dict, *, whitelist_attributes: Optional[list] = None, recursion: bool) dict

Delete keys with None values from dictionary.

Parameters:
  • source (dict) – dict object from which none values will be deleted

  • whitelist_attributes (list) – keyword-only argument containing name of attribute, which should be left alone even if they contain none values

  • recursion (bool) – flag that turns recursion on or off

mstrio.utils.helper.deprecation_warning(deprecated: str, new: str, version: str, module: bool = True, change_compatible_immediately=True)

This function is used to provide a user with a warning, that a given functionality is now deprecated, and won’t be supported from a given version.

Parameters:
  • deprecated (str) – name of a functionality that is deprecated

  • new (str) – name of a functionality that replaces deprecated one

  • version (str) – version from which deprecated functionality won’t be

  • supported

  • module (bool, optional) – Whether deprecated functionality is a module.

  • True. (functionality can be used immediately. Defaults to) –

  • change_compatible_immediately (bool, optional) – Whether the new

  • True.

mstrio.utils.helper.dict_compare(d1, d2)
mstrio.utils.helper.exception_handler(msg, exception_type=<class 'Exception'>, stack_lvl=2)

Generic error message handler.

Parameters:
  • msg (str) – Message to print in the Exception or Warning

  • exception_type (Exception) – Instance of Exception or Warning class

  • stack_lvl (int, optional) – controls how deep the stacktrace will be

mstrio.utils.helper.extract_all_dict_values(list_of_dicts: List[Dict]) List[Any]

Extract list of dicts values into list.

mstrio.utils.helper.fallback_on_timeout(min_limit: int = 50)

Return a decorator, which decorates a function with one argument, limit, to retry with half as big limit if it encounters a timeout error.

Do note that the wrapped function will return a (result, working_limit) tuple, not just the result, to allow for using the working limit further.

Parameters:

min_limit – The minimum limit that will be attempted as retry. If the wrapper recurses past it, it will just raise the error back.

mstrio.utils.helper.fallback_to_conn_project_id(connection: Connection) Optional[str]
mstrio.utils.helper.fetch_objects(connection: Connection, api: Callable, limit: Optional[int], filters: dict, error_msg: Optional[str] = None, dict_unpack_value: Optional[str] = None, **kwargs) list

Fetch and prepare objects. Optionally filter the objects by using the filters parameter. This function only supports endpoints without pagination.

Parameters:
  • connection – MicroStrategy REST API connection object

  • api – GET API wrapper function that will return list of objects in bulk

  • dict_unpack_value – if the response needs to be unpacked to get into the values specify the keyword

  • limit – cut-off value for the number of objects returned

  • error_msg – specifies error_msg for failed requests

  • **filters – dict that specifies filter expressions by which objects will be filtered locally

  • kwargs – all specific parameters that the api methods require that need to be additionally specified

mstrio.utils.helper.fetch_objects_async(connection: Connection, api: Callable, async_api: Callable, limit: Optional[int], chunk_size: int, filters: dict, error_msg: Optional[str] = None, dict_unpack_value: Optional[str] = None, **kwargs) list

Get all objects asynchronously. Optionally filter the objects using filters parameter. Works only for endpoints with limit and offset query parameter (pagination).

Parameters:
  • connection – MicroStrategy REST API connection object

  • api – GET API wrapper function that will return list of objects in bulk

  • async_api – asynchronous wrapper of the api function

  • dict_unpack_value – if the response needs to be unpacked to get into the values, specify the keyword

  • limit – cut-off value for the number of objects returned

  • chunk_size – number of objects in each chunk

  • error_msg – specifies error_msg for failed requests

  • **filters – dict that specifies filter expressions by which objects will be filtered locally

  • kwargs – all specific parameters that the api methods require that need to be additionally specified

mstrio.utils.helper.filter_obj_list(obj_list: List[T], **filters: Dict[str, Any]) List[T]

Filter a list of objects by providing one or more key-value pair filters.

mstrio.utils.helper.filter_params_for_func(func: Callable, params: dict, exclude: Optional[list] = None) dict

Filter dict of parameters and return only those that are parameters of a func. Mainly used in EntityBase.alter(), before calling EntityBase._alter_properties() as shown in Example.

Parameters:
  • func – a function that the params are going to be fit for

  • params – a dict with parameters that will be filtered

  • exclude – set exclude parameter to exclude specific param-value pairs

Returns:

a dict with parameters of func that exist in params dict

Example

params = filter_params_for_func(self.alter, locals()) self._alter_properties(**params)

mstrio.utils.helper.flatten2list(object) list

Flatten to list nested objects of type list, tuple, sets.

mstrio.utils.helper.get_args_from_func(func: Callable[[Any], Any])
mstrio.utils.helper.get_default_args_from_func(func: Callable[[Any], Any])
mstrio.utils.helper.get_objects_id(obj, obj_class)
mstrio.utils.helper.get_parallel_number(total_chunks)

Returns the optimal number of threads to be used for downloading cubes/reports in parallel.

mstrio.utils.helper.get_valid_project_id(connection: Connection, project_id: Optional[str] = None, project_name: Optional[str] = None, with_fallback: bool = False)

Check if the project name exists and return the project ID.

Parameters:
  • connection (object) – MicroStrategy connection object

  • project_id – Project ID

  • project_name (found based on) – Project name

  • with_fallback – Specify if the project should be taken from connection

  • be (object if project_id is not specified and the project failed to) –

  • project_name

mstrio.utils.helper.get_valid_project_name(connection: Connection, project_id: str)

Returns project name of given project based on its ID.

Parameters:
  • connection (object) – MicroStrategy connection object

  • project_id – Project ID

mstrio.utils.helper.is_document(view_media: int)

Documents and dossiers have the same type and subtype when returned from search api. They can be distinguished only by view_media value.

mstrio.utils.helper.is_dossier(view_media: int)

Documents and dossiers have the same type and subtype when returned from search api. They can be distinguished only by view_media value.

mstrio.utils.helper.list_folders(connection, name: Optional[str] = None, to_dataframe: bool = False, limit: Optional[int] = None, **filters) Union[List[dict], DataFrame]

List folders.

Parameters:
  • connection – MicroStrategy connection object returned by connection.Connection().

  • name (string, optional) – exact name of a folder to filter results. If None, all folders will be retrieved.

  • to_dataframe (bool, optional) – determine if result of retrieval will be returned as a list of dicts or DataFrame.

  • limit – limit the number of elements returned. If None (default), all objects are returned.

  • **filters – Available filter parameters: [‘id’, ‘name’, ‘subtype’, ‘type’,’date_created’, ‘date_modified’, ‘version’, ‘acg’, ‘owner’]

Returns:

When to_dataframe set to False (default value) then DataFrame with folders, otherwise list of dictionaries with folders.

mstrio.utils.helper.merge_id_and_type(object_id: str, object_type: Union[ObjectTypes, ObjectSubTypes, int], error_msg: Optional[str] = None) str
mstrio.utils.helper.response_handler(response, msg, throw_error=True, verbose=True, whitelist=None)

Generic error message handler for transactions against I-Server.

Parameters:
  • response – Response object returned by HTTP request.

  • msg (str) – Message to print in addition to any server-generated error message(s)

  • throw_error (bool) – Flag indicates if the error should be thrown

  • verbose (bool, optional) – controls if messages/errors will be printed

  • whitelist (list) – list of tuples of I-Server Error and HTTP errors codes respectively, which will not be handled i.e. whitelist = [(‘ERR001’, 500),(‘ERR004’, 404)]

mstrio.utils.helper.rgetattr(obj, attr, *default)

Recursive getattr. Third parameter is the default value.

Parameters:
  • obj – An object that is inspected

  • attr – attribute name chain/path

  • default (optional) – value returned if ‘attr’ not found

Returns:

value of ‘attr’ on success. On failure, default value.

Raises:
  • AttributeError on failure, when the 'attr' is incorrect

  • and no default provided

Example

rgetattr(obj, ‘attr1.attr2’, ‘default value’)

mstrio.utils.helper.rsetattr(obj, attr, val)

Recursive setattr. This can only modify last attr in the chain. For example rsetattr(obj, ‘attr1.attr2.attr3’, new_value) won’t work if attr2 doesn’t exist.

Parameters:
  • obj – An object that is edited

  • attr – attribute name chain/path

  • val – new value

Returns:

None on success

Raises:

AttributeError on failure, when the 'attr' is incorrect

Example

rsetattr(obj, ‘attr1.attr2’, new_value)

mstrio.utils.helper.snake_to_camel(response: Union[dict, list], whitelist: list[str] = None) Union[dict, List[dict]]

Converts dictionary keys from snake_case to camelCase. It works recursively for dicts in dicts.

mstrio.utils.helper.sort_object_properties(source: dict) int

Sort all properties of an object representing an MSTR object.

mstrio.utils.helper.url_check(url)

Checks the validity of the url required in the connection object and returns a validated url.

mstrio.utils.helper.validate_param_value(param_name, param_val, data_type, max_val=None, min_val=None, special_values=None, regex=None, exception=True, valid_example=None) bool

Validate param data type and optionally max, min special values.

Raises:
  • TypeError

  • ValueError

mstrio.utils.helper.version_cut(version)

mstrio.utils.model module

class mstrio.utils.model.Model(tables, name, description=None, folder_id=None, ignore_special_chars=False)

Bases: object

Internal utility for generating the definition of multi-table and single-table datasets.

Create the definition of a super cube containing one or more tables. The definition includes the name and description of the super cube and the name and description of each table, attribute, and metric within the super cube.

Attributes:

get_model()

Return the model object.

mstrio.utils.monitors module

mstrio.utils.monitors.all_nodes_async(connection, async_api: Callable, filters: dict, error_msg: str, unpack_value: Optional[str] = None, limit: Optional[int] = None, **kwargs)

Return list of objects fetched async using wrappers in monitors.py

mstrio.utils.object_mapping module

class mstrio.utils.object_mapping.SubTypeObjectMapping(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Filter = ObjectSubTypes.FILTER
OlapCube = ObjectSubTypes.OLAP_CUBE
SuperCube = ObjectSubTypes.SUPER_CUBE
User = ObjectSubTypes.USER
UserGroup = ObjectSubTypes.USER_GROUP
class mstrio.utils.object_mapping.TypeObjectMapping(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Attribute = ObjectTypes.ATTRIBUTE
DatasourceConnection = ObjectTypes.DBCONNECTION
DatasourceInstance = ObjectTypes.DBROLE
DatasourceLogin = ObjectTypes.DBLOGIN
Document = ObjectTypes.DOCUMENT_DEFINITION
Fact = ObjectTypes.FACT
Filter = ObjectTypes.FILTER
Folder = ObjectTypes.FOLDER
LogicalTable = ObjectTypes.TABLE
Metric = ObjectTypes.METRIC
Project = ObjectTypes.PROJECT
Report = ObjectTypes.REPORT_DEFINITION
Schedule = ObjectTypes.SCHEDULE_TRIGGER
SearchObject = ObjectTypes.SEARCH
SecurityFilter = ObjectTypes.SECURITY_FILTER
SecurityRole = ObjectTypes.SECURITY_ROLE
Shortcut = ObjectTypes.SHORTCUT_TYPE
Transformation = ObjectTypes.ROLE
UserHierarchy = ObjectTypes.DIMENSION
mstrio.utils.object_mapping.map_object(connection: Connection, obj: dict)

Map a dict that represents an object to an instance of the corresponding mstrio class.

mstrio.utils.object_mapping.map_objects_list(connection: Connection, objects_list: list)

Map a list of dict that represent objects to instances of the corresponding mstrio classes.

mstrio.utils.object_mapping.map_to_object(object_type: int | mstrio.types.ObjectTypes, subtype: Optional[Union[int, ObjectSubTypes]] = None)

mstrio.utils.parser module

class mstrio.utils.parser.Parser(response, parse_cube=True)

Bases: object

Converts JSON-formatted cube and report data into a tabular structure.

AF_COL_SEP = '@'
chunk_size = None
parse(response)
Parameters:

response – JSON-formatted content of API response.

total_rows = None

mstrio.utils.progress_bar_mixin module

class mstrio.utils.progress_bar_mixin.ProgressBarMixin

Bases: object

mstrio.utils.sessions module

class mstrio.utils.sessions.FuturesSessionWithRenewal(*, connection, **kwargs)

Bases: FuturesSession

request(*args, **kwargs)

Maintains the existing api for Session.request.

Used by all of the higher level methods, e.g. Session.get.

The background_callback param allows you to do some processing on the response in the background, e.g. call resp.json() so that json parsing happens in the background thread.

:rtype : concurrent.futures.Future

mstrio.utils.sessions.log_request(logger)
mstrio.utils.sessions.renew_session(func)

mstrio.utils.time_helper module

class mstrio.utils.time_helper.DatetimeFormats(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

DATE = '%Y-%m-%d'
FULLDATETIME = '%Y-%m-%dT%H:%M:%S.%f%z'
YMD = '%Y-%m-%d'
YMDHMS = '%Y-%m-%dT%H:%M:%S%z'
YMDHMSmS = '%Y-%m-%dT%H:%M:%S.%f%z'
mstrio.utils.time_helper.bulk_datetime_to_str(source: dict, string_to_date_map: dict, only_datetimefomat: bool = True) dict

Change all dates from source found in string_to_date_map to string format. If parameter is not found in string_to_date_map, it is returned without changes.

mstrio.utils.time_helper.bulk_str_to_datetime(source: dict, string_to_date_map: dict, only_datetimefomat: bool = True) dict

Change all dates from source found in string_to_date_map to datetime format. If parameter is not found in string_to_date_map, it is returned without changes.

mstrio.utils.time_helper.datetime_to_str(date: datetime, format_str: str) Optional[str]

Get date string from datetime, based on format_str provided. If date is already a string, return it. Make the date aware.

mstrio.utils.time_helper.map_datetime_to_str(name: str, date: datetime, string_to_date_map: dict, only_datetimefomat: bool = True) str

Change date format to string, based on string_to_date_map conversion dict. All occurrences of DATETIMEFORMAT Enum in string_to_date_map are converted to corresponding string values. If name is not found in string_to_date_map, returns date without changes.

mstrio.utils.time_helper.map_str_to_datetime(name: str, date: str, string_to_date_map: dict, only_datetimefomat: bool = True) datetime

Change date format to datetime, based on string_to_date_map conversion dict. All occurrences of DATETIMEFORMAT Enum in string_to_date_map are converted to corresponding string values. If name is not found in string_to_date_map, returns date without changes.

mstrio.utils.time_helper.override_datetime_format(original_format: str, expected_format: str, fields: tuple, to_unpack=None)

A decorator designed to override the datetime format of some dates in responses from REST server as they can be a bit crazy sometimes (e.g. two different formats for one object)

Parameters:
  • original_format – original format of a datetime

  • expected_format – the format you want to convert to

  • fields – fields of the object - e.g. dateModified, dateCreated

  • to_unpack – when response returns a list of objects probably they need to be unpacked

mstrio.utils.time_helper.str_to_datetime(date: str, format_str: str) Optional[datetime]

Change date format to datetime, based on format_str provided. If date is already a datetime object, return it. Make the date aware.

mstrio.utils.version_helper module

mstrio.utils.version_helper.class_version_handler(version)

Decorator which can be used on a class. It applies the method_version_handler decorator to all the methods in the decorated class that are not inherited.

mstrio.utils.version_helper.is_server_min_version(connection: Connection, version_str: str) bool

Check if iServer version is greater or equal than given version.

Parameters:
  • connection (Connection) – MicroStrategy REST API connection object

  • version_str (str) – String containg iServer version number

Returns:

True if iServer version is greater or equal to given version. False if iServer version is lower than given version.

mstrio.utils.version_helper.method_version_handler(version)

Decorator which can be applied to a function. When applied, validates the iServer version of the existing connection (retrieved from kwargs, args or connection property from self) and compares it with the version provided in the arguments - version at which the functionality becomes applicable.

mstrio.utils.wip module

class mstrio.utils.wip.WipLevels(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

ERROR = 5
INFO = 3
PREVIEW = 2
SILENT = 1
WARNING = 4
mstrio.utils.wip.filter_wip(iterable, return_wip: bool = False)
Return a generator containing only non-WIP elements

(or only WIP elements, depending on return_wip parameter.).

Parameters:
  • iterable – Any iterable containing elements that may or may not be WIP.

  • return_wip – Whether to return only WIP results or the opposite. Default False (return only non-WIP).

mstrio.utils.wip.filter_wip_dict(dict: dict, return_wip: bool = False) dict
Return a dict containing only non-WIP elements

(or only WIP elements, depending on return_wip parameter.).

Parameters:
  • dict – Any dict containing elements that may or may not be WIP.

  • return_wip – Whether to return only WIP results or the opposite. Default False (return only non-WIP).

mstrio.utils.wip.is_module_wip(module_globals: dict) bool
mstrio.utils.wip.is_wip(obj) bool
mstrio.utils.wip.module_wip(module_globals: dict, target_release: Optional[Union[Version, str]] = None, level: WipLevels = WipLevels.WARNING, message: Optional[str] = None, prefix_doc: Union[bool, str] = True, mark_attr: bool = True)

Emit the WIP warning/error/info when the module is loaded.

mstrio.utils.wip.pause_wip_warnings()
mstrio.utils.wip.resume_wip_warnings(previous_setting: bool)
mstrio.utils.wip.wip(target_release: Optional[Union[Version, str]] = None, level: WipLevels = WipLevels.WARNING, message: Optional[str] = None, prefix_doc: Union[bool, str] = True, mark_attr: bool = True)

Work-In-Progress wrapper

Note

This is a decorator generator, which accepts arguments and returns the actual decorator, so even when not providing arguments and letting it choose the defaults it should be used like @wip(), not plain @wip.

Parameters:
  • target_release – The target release when the functionality is scheduled to be production-ready.

  • level – The severity level of the warning emitted when the functionality is loaded or used. SILENT: no warning will be emitted PREVIEW: a warning will be dispatched INFO: a disclaimer will be printed to stderr WARNING: a warning will be dispatched ERROR: an error will be raised

  • message – A custom message to replace the one standard to the given level

  • prefix_doc – Whether to prefix the docstring with a WIP warning. Accepts bool values or a custom string to replace standard prefix.

  • mark_attr – Marks the wrapped function via adding the _wip attribute, which is checked by is_wip.

Module contents