Roles¶
Roles(baze)
¶
Class used for handling roles.
Source code in echo_baze/baze_root.py
def __init__(self, baze: e_bz.Baze) -> None:
"""Base class that all subclasses should inherit from.
Parameters
----------
baze : Baze
Top level object carrying all functionality and the connection handler.
"""
# check inputs
if not isinstance(baze, e_bz.Baze):
raise ValueError(f"baze must be of type Baze, not {type(baze)}")
self.baze: e_bz.Baze = baze
get(output_type='dict', names=None)
¶
Gets all roles with detailed information.
The most useful keys/columns returned are:
- id
- description
- disabled
- permissions (only available if names is not None)
Parameters:
-
(output_type¶Literal['dict', 'DataFrame'], default:'dict') –Output type of the data. Can be one of ["dict", "DataFrame"] By default "dict"
-
(names¶list[str] | None, default:None) –List of names of the roles to be retrieved. If this is provided, more information will be provided like the permissions. If None, all roles will be retrieved, by default None
Returns:
-
dict[str, dict[str, Any]]–In case output_type == "dict" it will return a dict with the following format: {name: {attribute: value, ...}, ...}
-
DataFrame–In case output_type == "DataFrame" it will return a DataFrame with the following format: index = name, columns = [attribute, ...]
Source code in echo_baze/roles.py
@validate_call
def get(
self,
output_type: Literal["dict", "DataFrame"] = "dict",
names: list[str] | None = None,
) -> dict[str, dict[str, Any]] | DataFrame:
"""Gets all roles with detailed information.
The most useful keys/columns returned are:
- id
- description
- disabled
- permissions (only available if names is not None)
Parameters
----------
output_type : Literal["dict", "DataFrame"], optional
Output type of the data. Can be one of ["dict", "DataFrame"]
By default "dict"
names : list[str] | None, optional
List of names of the roles to be retrieved. If this is provided, more information will be provided like the permissions.
If None, all roles will be retrieved, by default None
Returns
-------
dict[str, dict[str, Any]]
In case output_type == "dict" it will return a dict with the following format: {name: {attribute: value, ...}, ...}
DataFrame
In case output_type == "DataFrame" it will return a DataFrame with the following format: index = name, columns = [attribute, ...]
"""
# getting all
if names is None:
endpoint = "roles"
# getting the data
result = self.baze.conn.get(endpoint)
self._handle_http_errors(result)
# converting to dict
result: list[dict[str, Any]] = result.json()
else:
ids = self.get_ids()
result = []
for name in names:
if name not in ids:
logger.warning(f"Role with name '{name}' does not exist, skipping")
endpoint = f"roles/{ids[name]}"
# getting the data
this_result = self.baze.conn.get(endpoint)
self._handle_http_errors(this_result)
result.append(this_result.json())
if not result:
raise ValueError("None of the desired role names exist!")
# returning on the desired format
match output_type:
case "dict":
# defining the name as the key for the dict
result_dict = {entry["name"]: entry for entry in result}
# removing the name from the dict values
for entry in result_dict.values():
del entry["name"]
return result_dict
case "DataFrame":
df = json_normalize(result, max_level=1)
df = df.convert_dtypes(dtype_backend="pyarrow")
df = df.set_index("name")
return df
case _:
raise ValueError(f"Invalid output_type: {output_type}")
get_ids()
¶
Gets a dictionary with all role names and ids.
Returns:
-
dict[str, int]:–Dictionary with all roles in the format {name: id, ...}
Source code in echo_baze/roles.py
def get_ids(self) -> dict[str, int]:
"""Gets a dictionary with all role names and ids.
Returns
-------
dict[str, int]:
Dictionary with all roles in the format {name: id, ...}
"""
endpoint = "roles"
# getting the data
result = self.baze.conn.get(endpoint)
self._handle_http_errors(result)
# converting to dict
result: list[dict[str, Any]] = result.json()
return {entry["name"]: entry["id"] for entry in result}
update(name, new_name=None, description=None, disabled=None, permissions=None)
¶
Updates a role. Only arguments that are not None will be updated, the rest will be left as they are now.
Parameters:
-
(name¶str) –Name of the role to be updated.
-
(new_name¶str | None, default:None) –New name for the role (will change the one provided), by default None
-
(description¶str | None, default:None) –New description for the role, by default None
-
(disabled¶bool | None, default:None) –New disabled status for the role, by default None
-
(permissions¶list[str] | None, default:None) –New permissions for the role, by default None
Source code in echo_baze/roles.py
@validate_call
def update(
self,
name: str,
new_name: str | None = None,
description: str | None = None,
disabled: bool | None = None,
permissions: list[str] | None = None,
) -> None:
"""Updates a role. Only arguments that are not None will be updated, the rest will be left as they are now.
Parameters
----------
name : str
Name of the role to be updated.
new_name : str | None, optional
New name for the role (will change the one provided), by default None
description : str | None, optional
New description for the role, by default None
disabled : bool | None, optional
New disabled status for the role, by default None
permissions : list[str] | None, optional
New permissions for the role, by default None
"""
# checking inputs
if not isinstance(name, str):
raise TypeError(f"name must be a string, got {type(name)}")
if not isinstance(new_name, str | type(None)):
raise TypeError(f"new_name must be a string or None, got {type(new_name)}")
if not isinstance(description, str | type(None)):
raise TypeError(f"description must be a string or None, got {type(description)}")
if not isinstance(disabled, bool | type(None)):
raise TypeError(f"disabled must be a bool or None, got {type(disabled)}")
if not isinstance(permissions, list | type(None)):
raise TypeError(f"permissions must be a list or None, got {type(permissions)}")
args = {"new_name": new_name, "description": description, "disabled": disabled, "permissions": permissions}
# checking if role with desired name exists
if name not in self.get_ids():
raise ValueError(f"Role with name '{name}' does not exist")
# checking if at least one of the arguments is not None
if all(arg is None for arg in args.values()):
raise ValueError("At least one of the arguments must be different from None")
# getting the existing role
current = self.get(output_type="dict", names=[name])[name]
# creating dict that will be used to update
new = deepcopy(current)
# adding name to new_role
new["name"] = name
# updating new_role with the new values
if new_name is not None:
new["name"] = new_name
for arg, arg_value in args.items():
if arg != "new_name" and arg_value is not None:
new[arg] = arg_value
# updating modified date using format 0001-01-01T00:00:00.0000000
new["modifiedDate"] = datetime.now(UTC).isoformat()
endpoint = "roles"
# sending the data
result = self.baze.conn.post(endpoint, json=new)
self._handle_http_errors(result)