magpie.api.webhooks¶
Attributes¶
Classes¶
Utility |
|
Supported Webhook actions. |
Functions¶
|
Obtains the JSON formatted Group definition according to field selection flags. |
|
Formats a Resource information into JSON. |
|
Formats a Service information into JSON. |
|
Formats a User information into JSON. |
|
Search in order for matched value of |
|
|
Loads all matched configurations. |
|
|
Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when |
|
Retrieve application settings from a supported container. |
|
Logs the provided message to the logger and raises the corresponding exception afterwards. |
|
Returns a visual representation of a function signature with is arguments. |
Generates the Webhook parameters based on provided references. |
|
|
Checks the config for any webhooks that correspond to the input action, and prepares corresponding requests. |
|
Generates a callback URL using Magpie temporary tokens for use by the webhook implementation. |
|
Replace each template parameter from the payload by its corresponding value. |
|
Sends a single webhook request using the input config. |
|
Updates the user's status to indicate an error occurred with the webhook requests. |
|
Prepares and validates Webhook settings for the application based on definitions in configuration file(s). |
Module Contents¶
- magpie.api.webhooks.format_group(group: magpie.models.Group, basic_info: bool = False, public_info: bool = False, dotted: bool = False, db_session: sqlalchemy.orm.session.Session | None = None) magpie.typedefs.JSON[source]¶
Obtains the JSON formatted Group definition according to field selection flags.
- Parameters:
group – Group for which to provide details.
basic_info – If
True, return only sufficient details to identify the group (useful for routes that refer to a group, but that are not requesting it specifically), or return full details (for routes that specifically request its information, e.g.:GET /groups/{grp}).public_info – Indicate if the returned details are intended for public information (
True) or admin-only (False). Only higher level users should be provided additional details to avoid leaking potentially sensitive parameters.dotted – Employ a dot (
.) instead of underscore (_) to separate Group from its basic information.db_session – Database connection to retrieve additional details (required when
public_info=False).
- magpie.api.webhooks.format_resource(resource: magpie.models.Resource, permissions: Collection[magpie.typedefs.AnyPermissionType] | None = None, permission_type: magpie.permissions.PermissionType | None = None, basic_info: bool = False, dotted: bool = False) magpie.typedefs.JSON[source]¶
Formats a Resource information into JSON.
- Parameters:
resource – Resource 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.basic_info – If
True, return only sufficient details to identify the resource, without any additionalpermissionsdetail, nor hierarchicalresourceinformation is returned.dotted – Employ a dot (
.) instead of underscore (_) to separate Resource from its basic information.
- magpie.api.webhooks.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
permissionsof theserviceif not specified. To preserve empty permissions such as during listing of user/group resource permissions, an emptylistshould be specified.- Parameters:
service – Service 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 aboutpermissions, children resources or configuration information is returned.dotted – Employ a dot (
.) instead of underscore (_) to separate Service from its basic information.
- magpie.api.webhooks.format_user(user: magpie.models.AnyUser, group_names: List[magpie.typedefs.Str] = None, basic_info: bool = False, dotted: bool = False) magpie.typedefs.JSON[source]¶
Formats a User information into JSON.
- Parameters:
user – User to be formatted.
group_names – Override of group name listing to provide as user memberships. Retrieve the complete group membership listing from the
userif not provided.basic_info – If
True, return only sufficient details to identify the User, without any additional group details.dotted – Employ a dot (
.) instead of underscore (_) to separate User from its basic information.
- magpie.api.webhooks.get_constant(constant_name: magpie.typedefs.Str, settings_container: magpie.typedefs.AnySettingsContainer | None = None, settings_name: magpie.typedefs.Str | None = None, default_value: magpie.typedefs.SettingValue | None = None, raise_not_set: bool = True, raise_missing: bool = True, print_missing: bool = False, empty_missing: bool = False) magpie.typedefs.SettingValue[source]¶
- Search in order for matched value of
constant_name: search in
MAGPIE_CONSTANTSsearch in settings if specified
search alternative setting names (see below)
search in
magpie.constantsdefinitionssearch in environment variables
Parameter
constant_nameis expected to have the formatMAGPIE_[VARIABLE_NAME]although any value can be passed to retrieve generic settings from all above-mentioned search locations.If
settings_nameis provided as alternative name, it is used as is to search for results ifconstant_namewas not found. Otherwise,magpie.[variable_name]is used for additional search when the formatMAGPIE_[VARIABLE_NAME]was used forconstant_name(i.e.:MAGPIE_ADMIN_USERwill also search formagpie.admin_userand so on for corresponding constants).- Parameters:
constant_name – key to search for a value
settings_container – WSGI application settings container (if not provided, uses found one in current thread)
settings_name – alternative name for settings if specified
default_value – default value to be returned if not found anywhere, and exception raises are disabled.
raise_not_set – raise an exception if the found key is
None, search until last case if others areNoneraise_missing – raise exception if key is not found anywhere
print_missing – print message if key is not found anywhere, return
Noneempty_missing – consider an empty value for an existing key as if it was missing (i.e.: as if not set).
- Returns:
found value or default_value
- Raises:
ValueError – if resulting value is invalid based on options (by default raise missing/empty/
Nonevalue)LookupError – if no appropriate value could be found from all search locations (according to options)
- Search in order for matched value of
- magpie.api.webhooks.get_db_session_from_config_ini(config_ini_path, ini_main_section_name='app:magpie_app', settings_override=None)[source]¶
- magpie.api.webhooks.get_all_configs(path_or_dict: magpie.typedefs.Str | magpie.typedefs.CombinedConfig, section: magpie.typedefs.Literal[groups], allow_missing: bool = False) magpie.typedefs.GroupsConfig[source]¶
- magpie.api.webhooks.get_all_configs(path_or_dict: magpie.typedefs.Str | magpie.typedefs.CombinedConfig, section: magpie.typedefs.Literal[users], allow_missing: bool = False) magpie.typedefs.UsersConfig
- magpie.api.webhooks.get_all_configs(path_or_dict: magpie.typedefs.Str | magpie.typedefs.CombinedConfig, section: magpie.typedefs.Literal[permissions], allow_missing: bool = False) magpie.typedefs.PermissionsConfig
- magpie.api.webhooks.get_all_configs(path_or_dict: magpie.typedefs.Str | magpie.typedefs.CombinedConfig, section: magpie.typedefs.Literal[services], allow_missing: bool = False) magpie.typedefs.ServicesConfig
- magpie.api.webhooks.get_all_configs(path_or_dict: magpie.typedefs.Str | magpie.typedefs.CombinedConfig, section: magpie.typedefs.Literal[webhooks], allow_missing: bool = False) magpie.typedefs.WebhooksConfig
Loads all matched configurations.
Configurations are considered a valid match if they have one of the
CONFIG_KNOWN_EXTENSIONS(if path) and that loaded (or passed) configurations contain the specifiedsectionname.If the input is a directory path, loads any number of files contained in it that fulfill matching conditions. If it is a path pointing to a single valid configuration file, loads it by itself. If a dictionary is passed, returns it directly if it fulfills validation.
- Parameters:
path_or_dict – directory path, file path or literal dictionary.
section – section name that must be inside every matched configuration file to be loaded.
allow_missing – allow to have no valid configuration after all are resolved, otherwise raises.
- Raises:
RegistrationError – when no valid configuration can be found and empty one is not allowed.
- Returns:
list of configurations loaded if input was a directory path
list of single configuration if input was a file path
list of single configuration if input was a JSON dict
empty list if none of the other cases where matched
Note
Order of file loading will be resolved by alphabetically sorted filename if specifying a directory path.
- class magpie.api.webhooks.ExtendedEnum[source]¶
Bases:
enum.EnumUtility
enum.Enummethods.Create an extended enum with these utilities as follows:
class CustomEnum(ExtendedEnum): ItemA = "A" ItemB = "B"
- classmethod names() List[magpie.typedefs.Str][source]¶
Returns the member names assigned to corresponding enum elements.
- classmethod values() List[magpie.typedefs.AnyKey][source]¶
Returns the literal values assigned to corresponding enum elements.
- classmethod get(key_or_value: magpie.typedefs.AnyKey, default: Any | None = None) _TC | None[source]¶
Finds an enum entry by defined name or its value.
Returns the entry directly if it is already a valid enum.
- classmethod titles() List[magpie.typedefs.Str][source]¶
Returns the title representation of all enum elements.
- property title: magpie.typedefs.Str¶
Returns the title representation of the enum element.
Title use the original enum element name with capitalization considering underscores for separate words.
- magpie.api.webhooks.get_logger(name: magpie.typedefs.Str, level: int | None = None, force_stdout: bool = None, message_format: magpie.typedefs.Str | None = None, datetime_format: magpie.typedefs.Str | None = None) logging.Logger[source]¶
Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when level is
logging.NOTSET.
- magpie.api.webhooks.get_settings(container: magpie.typedefs.AnySettingsContainer | None, app: bool = False) magpie.typedefs.SettingsType[source]¶
Retrieve application settings from a supported container.
- Parameters:
container – supported container with a handle to application settings.
app – allow retrieving from current thread registry if no container was defined.
- Returns:
found application settings dictionary.
- Raises:
TypeError – when no application settings could be found or unsupported container.
- magpie.api.webhooks.raise_log(msg: magpie.typedefs.Str, exception: Type[Exception] = Exception, logger: logging.Logger | None = None, level: int = logging.ERROR) NoReturn[source]¶
Logs the provided message to the logger and raises the corresponding exception afterwards.
- Raises:
exception – whichever exception provided is raised systematically after logging.
- magpie.api.webhooks.signature_with_args(func: Callable[[Ellipsis], Any], *args: Any, **kwargs: Any) magpie.typedefs.Str[source]¶
Returns a visual representation of a function signature with is arguments.
def function(a, b, c=1): ... signature_with_args(function, 1, 2, c=3) # returns: <module.function(a=1, b=2, c=3)>
- magpie.api.webhooks.WEBHOOK_TEMPLATE_PARAMS = ['group.name', 'group.id', 'user.name', 'user.id', 'user.email', 'user.status', 'resource.id',...[source]¶
- magpie.api.webhooks.WEBHOOK_HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'][source]¶
- class magpie.api.webhooks.WebhookAction[source]¶
Bases:
magpie.utils.ExtendedEnumSupported Webhook actions.
- DELETE_USER = 'delete_user'[source]¶
Triggered when an existing User gets successfully deleted.
See also
- UPDATE_USER_STATUS = 'update_user_status'[source]¶
Triggered when an existing User status gets successfully updated.
See also
- CREATE_USER_PERMISSION = 'create_user_permission'[source]¶
Triggered when a Permission onto a Service or Resource gets created for a User.
See also
- DELETE_USER_PERMISSION = 'delete_user_permission'[source]¶
Triggered when a Permission onto a Service or Resource gets deleted for a User.
See also
- CREATE_GROUP_PERMISSION = 'create_group_permission'[source]¶
Triggered when a Permission onto a Service or Resource gets created for a Group.
See also
- magpie.api.webhooks.get_permission_update_params(target: magpie.models.User | magpie.models.Group, resource: magpie.typedefs.ServiceOrResourceType, permission: magpie.permissions.PermissionSet, db_session: sqlalchemy.orm.session.Session) magpie.typedefs.WebhookTemplateParameters[source]¶
Generates the Webhook parameters based on provided references.
- magpie.api.webhooks.process_webhook_requests(action: WebhookAction, params: magpie.typedefs.WebhookTemplateParameters, update_user_status_on_error: bool = False, settings: magpie.typedefs.AnySettingsContainer | None = None) None[source]¶
Checks the config for any webhooks that correspond to the input action, and prepares corresponding requests.
- Parameters:
action – tag identifying which webhooks to use in the config
params – Dictionary containing the required parameters and associated values for the request following the event action. Parameters will replace templates found in the
payloaddefinition of the webhook.update_user_status_on_error – update the user status or not in case of a webhook error.
settings – application settings where webhooks configuration can be retrieved.
- magpie.api.webhooks.generate_callback_url(operation: magpie.models.TokenOperation, db_session: sqlalchemy.orm.session.Session, user: magpie.models.AnyUser | None = None, group: magpie.models.Group | None = None) magpie.typedefs.Str[source]¶
Generates a callback URL using Magpie temporary tokens for use by the webhook implementation.
- Parameters:
operation – targeted operation that employs the callback URL for reference.
db_session – database session to store the generated temporary token.
user – user reference associated to the operation as applicable.
group – group reference associated to the operation as applicable.
- Returns:
generated callback URL.
- magpie.api.webhooks.replace_template(params: magpie.typedefs.WebhookTemplateParameters, payload: magpie.typedefs.WebhookPayload, force_str: bool = False) magpie.typedefs.WebhookPayload[source]¶
Replace each template parameter from the payload by its corresponding value.
- Parameters:
params – the values of the template parameters
payload – structure containing the data to be processed by the template replacement
force_str – enforce string conversion of applicable fields where non-string values are detected.
- Returns:
structure containing the data with the replaced template parameters
- magpie.api.webhooks.send_webhook_request(webhook_config: magpie.typedefs.WebhookConfigItem, params: magpie.typedefs.WebhookTemplateParameters, update_user_status_on_error: bool = False) None[source]¶
Sends a single webhook request using the input config.
- Parameters:
webhook_config – dictionary containing the config data of a single webhook
params – dictionary containing the required parameters for the request, they will replace templates found in the payload
update_user_status_on_error – update the user status or not in case of a webhook error
- magpie.api.webhooks.webhook_update_error_status(user_name: magpie.typedefs.Str) None[source]¶
Updates the user’s status to indicate an error occurred with the webhook requests.
- magpie.api.webhooks.setup_webhooks(config_path: magpie.typedefs.Str | None, settings: magpie.typedefs.SettingsType) None[source]¶
Prepares and validates Webhook settings for the application based on definitions in configuration file(s).
Following execution, all validated Webhook configurations will have every parameters defined in
WEBHOOK_KEYS, whether optional or mandatory. Required parameters inWEBHOOK_KEYS_REQUIREDare explicitly validated for defined value and raise if missing. Parameters fromWEBHOOK_KEYS_OPTIONALare defaulted toNoneif missing.Any Webhook failing validation will raise the whole configuration and not apply any changes to the
settings. Format validation is applied to some specific parameters to anticipate and raise definitions guaranteed to be erroneous to avoid waiting until runtime for them to fail upon their trigger event.See also
Documentation in Webhook Configuration.
- Parameters:
config_path – a single file or directory path where configuration file(s) with
webhooksection.settings – modified settings in-place with added valid webhooks.