magpie.api.management.service.service_formats

Attributes

SERVICE_TYPE_DICT

Classes

PermissionType

Applicable types of Permission according to context.

Functions

evaluate_call(→ Any)

Evaluates the specified call with a wrapped HTTP exception handling. On failure, tries to call.

format_resource_tree(→ magpie.typedefs.JSON)

Generates the formatted resource tree under the provided nested resources.

crop_tree_with_permission(...)

Recursively prunes all children resources from the tree hierarchy except listed ones matched by ID.

get_resource_children(...)

Obtains the children resource node structure of the input service or resource.

format_permissions(→ Dict[magpie.typedefs.Str, ...)

Obtains the formatted permission representations after validation that each of their name is a known member of

get_twitcher_protected_service_url(→ magpie.typedefs.Str)

Obtains the protected service URL behind Twitcher Proxy based on combination of supported configuration settings.

format_service(→ magpie.typedefs.JSON)

Formats a Service information into JSON.

format_service_resources(→ magpie.typedefs.JSON)

Formats the service and its children resource tree as a JSON body.

format_service_resource_type(→ magpie.typedefs.JSON)

Module Contents

magpie.api.management.service.service_formats.evaluate_call(call: Callable[[], Any], fallback: Callable[[], None] | None = None, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: magpie.typedefs.ParamsType | None = None, msg_on_fail: magpie.typedefs.Str = '', content: magpie.typedefs.JSON | None = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: magpie.typedefs.JSON | None = None) Any[source]

Evaluates the specified call with a wrapped HTTP exception handling. On failure, tries to call.

fallback if specified, and finally raises the specified http_error.

Any potential error generated by fallback or http_error themselves are treated as HTTPInternalServerError.

Exceptions are generated using the standard output method formatted based on specified content_type.

Example:

normal call:

try:
    res = func(args)
except Exception as exc:
    fb_func()
    raise HTTPExcept(exc.message)

wrapped call:

res = evaluate_call(lambda: func(args), fallback=lambda: fb_func(), http_error=HTTPExcept, **kwargs)
Parameters:
  • call – function to call, MUST be specified as lambda: <function_call>

  • fallback – function to call (if any) when call failed, MUST be lambda: <function_call>

  • http_error – alternative exception to raise on call failure

  • http_kwargs – additional keyword arguments to pass to http_error if called in case of HTTP exception

  • msg_on_fail – message details to return in HTTP exception if call failed

  • content – json formatted additional content to provide in case of exception

  • content_type – format in which to return the exception (one of magpie.common.SUPPORTED_ACCEPT_TYPES)

  • metadata – request metadata to add to the response body. (see: magpie.api.requests.get_request_info())

Raises:
  • http_error – on call failure

  • HTTPInternalServerError – on fallback failure

Returns:

whichever return value call might have if no exception occurred

magpie.api.management.service.service_formats.format_resource_tree(nested_resources: magpie.typedefs.NestedResourceNodes, db_session: sqlalchemy.orm.session.Session, resources_perms_dict: magpie.typedefs.ResourcePermissionMap | None = None, permission_type: magpie.permissions.PermissionType | None = None, nesting_key: magpie.typedefs.NestingKeyType = 'children') magpie.typedefs.JSON[source]

Generates the formatted resource tree under the provided nested resources.

For all of the nested resources, formatting is applied by calling format_resource() recursively on them. Apply specific resource permissions as defined by resources_perms_dict if provided.

Parameters:
  • nested_resources – Service or resource for which to generate the formatted resource tree.

  • db_session – Connection to database.

  • resources_perms_dict – Any pre-established Applied Permission to set to corresponding resources by ID. When provided, these will define the User, Group or both (i.e.: Inherited Permissions) actual permissions, or even the Effective Permissions, according to parent caller function’s context. Otherwise (None), defaults to extracting Allowed Permissions for the given Resource scoped under the corresponding root Service.

  • permission_type – Override Permission type to indicate its provenance. Type is applied recursively for all resources in the generated nested resource tree.

  • nesting_key – Key to employ for nesting the formatted sub-tree resources according to the provided nested resources.

Returns:

Formatted nested resource tree with their details and permissions.

magpie.api.management.service.service_formats.crop_tree_with_permission(children: magpie.typedefs.NestedResourceNodes, resource_id_list: List[int]) Tuple[magpie.typedefs.NestedResourceNodes, List[int]][source]

Recursively prunes all children resources from the tree hierarchy except listed ones matched by ID.

Input children is expected to be a dictionary of resource nodes and children resources with their ID as keys:

{
    <res-id>: {
        "node": <res>,
        "children": {
            <res-id>: {
                "node": <res>,
                "children": { <...> }
            },
            <...>
    },
    <...>
}
Parameters:
  • children – full hierarchy of children resource nodes.

  • resource_id_list – resource IDs of nodes to preserve.

Returns:

pruned hierarchy of resource nodes.

magpie.api.management.service.service_formats.get_resource_children(resource: magpie.typedefs.ServiceOrResourceType, db_session: sqlalchemy.orm.session.Session, tree_service_builder: ziggurat_foundations.models.services.resource_tree.ResourceTreeService | None = None, limit_depth: int | None = None) magpie.typedefs.NestedResourceNodes[source]

Obtains the children resource node structure of the input service or resource.

Parameters:
  • resource – Initial resource where to start building the tree from.

  • db_session – Database connection to retrieve resources.

  • tree_service_builder – Utility that build the tree (default: models.RESOURCE_TREE_SERVICE).

  • limit_depth – Maximum depth to look for children resources (very deep if not specified, could be slow).

Returns:

{node: Resource, children: {node_id: <recursive>}}

class magpie.api.management.service.service_formats.PermissionType[source]

Bases: magpie.utils.ExtendedEnum

Applicable types of Permission according to context.

ACCESS = 'access'
ALLOWED = 'allowed'
APPLIED = 'applied'
DIRECT = 'direct'
INHERITED = 'inherited'
EFFECTIVE = 'effective'
OWNED = 'owned'
magpie.api.management.service.service_formats.format_permissions(permissions: Collection[magpie.typedefs.AnyPermissionType] | None, permission_type: PermissionType | None = None, force_unique: bool = True) Dict[magpie.typedefs.Str, List[magpie.typedefs.Str] | magpie.typedefs.PermissionDict | magpie.typedefs.Str][source]

Obtains the formatted permission representations after validation that each of their name is a known member of Permission enum, and optionally with modifiers as defined by PermissionSet.

The returned lists are sorted alphabetically by permission name, and then in order of resolution priority (from highest to lowest) for each subset or corresponding name.

The permissions are cleaned from any duplicate entries, unless force_unique is specified to allow it. If no or empty permissions is provided, empty lists are returned.

Note

Field permission_names provides both the older implicit permission names and the newer explicit name representation. For this reason, there will be semantically “duplicate” permissions in that list, but there will not be any literal string duplicates. Implicit names are immediately followed by their explicit name, unless implicit names do not apply for the given permission (e.g.: when Access.DENY did not exist). Only detailed and explicit JSON representations are provided in the permissions list.

When permission_type is equal to PermissionType.ALLOWED, the collection of every applicable PermissionSet is automatically generated by expanding all combinations of Access and Scope with every provided Permission name in permissions. This allows more concise definition of allowed permissions under magpie.services.Services and their children Resource by only defining Permission names without manually listing all variations of PermissionSet.

For other permission_type values, which represent Applied Permission only explicitly provided permissions are returned, to effectively return the collection of active permissions.

Parameters:
  • permissions – multiple permissions of any implementation and type, to be rendered both as names and JSON.

  • permission_type – indication of the represented permissions to be formatted, for informative indication.

  • force_unique – whether to remove duplicate entries by association of name, access and scope or not.

Returns:

JSON with the permissions listed as implicit+explicit names, as permission set objects, and their type.

magpie.api.management.service.service_formats.SERVICE_TYPE_DICT[source]
magpie.api.management.service.service_formats.get_twitcher_protected_service_url(magpie_service_name: magpie.typedefs.Str, container: magpie.typedefs.AnySettingsContainer | None = None, hostname: magpie.typedefs.Str | None = None) magpie.typedefs.Str[source]

Obtains the protected service URL behind Twitcher Proxy based on combination of supported configuration settings.

See also

Documentation section Twitcher Settings for available setting combinations.

Parameters:
  • magpie_service_name – name of the service to employ in order to form the URL path behind the proxy.

  • container – container that provides access to application settings.

  • hostname – override literal hostname to generate the URL instead of resolving using settings.

Returns:

resolved Twitcher Proxy protected service URL

magpie.api.management.service.service_formats.format_service(service: magpie.models.Service, permissions: List[magpie.permissions.PermissionSet] | None = None, permission_type: magpie.permissions.PermissionType | None = None, show_private_url: bool = False, show_public_url: bool = True, show_resources_allowed: bool = False, show_configuration: bool = False, basic_info: bool = False, dotted: bool = False) magpie.typedefs.JSON[source]

Formats a Service information into JSON.

Note

Automatically finds permissions of the service if not specified. To preserve empty permissions such as during listing of user/group resource permissions, an empty list should be specified.

Parameters:
  • serviceService to be formatted.

  • permissions – Permissions to list along with the resource. By default, these are the applicable permissions for that corresponding resource type.

  • permission_type – Override indication of provenance to apply to permissions. Only applicable when they are provided.

  • show_private_url – Display the protected and private URL employed at service registration.

  • show_public_url – Display the generated public URL from configured Twitcher Settings.

  • show_resources_allowed – Display children resource details.

  • show_configuration – Display the applicable configuration of the Service if it supports it.

  • basic_info – If True, return only sufficient details to identify the service, without any additional details about permissions, children resources or configuration information is returned.

  • dotted – Employ a dot (.) instead of underscore (_) to separate Service from its basic information.

magpie.api.management.service.service_formats.format_service_resources(service: magpie.models.Service, db_session: sqlalchemy.orm.session.Session, service_perms: List[magpie.permissions.PermissionSet] | None = None, resources_perms_dict: magpie.typedefs.ResourcePermissionMap | None = None, permission_type: magpie.permissions.PermissionType | None = None, show_all_children: bool = False, show_private_url: bool = True) magpie.typedefs.JSON[source]

Formats the service and its children resource tree as a JSON body.

Parameters:
  • service – service for which to display details with sub-resources

  • db_session – database session

  • service_perms – If provided, sets all Applied Permission to display on the formatted service. Otherwise, sets Allowed Permissions specific to the service’s type.

  • resources_perms_dict – If provided (not None), set the Applied Permission on each specified resource matched by ID. If None, retrieve and set Allowed Permissions for the corresponding Resources under the Service. To set empty Applied Permission (e.g.: User doesn’t have permissions on that resource), provide an explicit empty dictionary instead.

  • permission_type – Provide permission type being rendered.

  • show_all_children – Display all children resources recursively, or only ones specified by ID with resources_perms_dict.

  • show_private_url – displays the

Returns:

JSON body representation of the service resource tree

magpie.api.management.service.service_formats.format_service_resource_type(resource_class: Type[magpie.models.Resource], service_class: Type[magpie.services.ServiceInterface]) magpie.typedefs.JSON[source]