Core
Core API reference
- class notifiers.core.SchemaResource[source]
Base class that represent an object schema and its utility methods
- _get_environs(prefix: str | None = None) dict[source]
Fetches set environment variables if such exist. Searches for [PREFIX_NAME][PROVIDER_NAME]_[ARGUMENT] for each of the arguments defined in the schema. Arguments with an alias (e.g.
from_with aliasfrom) can be set via either name, the alias wins.- Parameters:
prefix – The environ prefix to use. If not supplied, uses the default
- Returns:
A dict of arguments and value retrieved from environs
- _merge_defaults(data: dict) dict[source]
Convenience method that calls
merge_dicts()in order to merge default values- Parameters:
data – Notification data
- Returns:
A merged dict of provided data with added defaults
- _normalize_keys(data: dict) dict[source]
Renames arguments passed by field name to their alias (e.g.
from_tofrom), so they merge correctly with environs and defaults. If both names are passed, both are kept and validation rejects the duplicate.- Parameters:
data – Notification data
- Returns:
Data keyed by alias where relevant
- _prepare_data(data: dict) dict[source]
- Use this method to manipulate data that’ll fit the respected provider API.
For example, all provider must use the
messageargument but sometimes provider expects a different variable name for this, liketext.
- Parameters:
data – Notification data
- Returns:
Returns manipulated data, if there’s a need for such manipulations.
- _process_data(**data) dict[source]
- The main method that process all resources data. Validates schema, gets environs, validates data, prepares
it via provider requirements, merges defaults and check for data dependencies
- Parameters:
data – The raw data passed by the notifiers client
- Returns:
Processed data
- _validate_data(data: dict) dict[source]
Validates data against
schema_model. RaisesBadArgumentsif relevant- Parameters:
data – Data to validate
- Returns:
The validated data. Values may be coerced to their declared types (e.g.
"587"to587), and arguments are keyed by their alias (e.g.from_becomesfrom). Only arguments that were passed are included.- Raises:
- _validate_data_dependencies(data: dict) dict[source]
Validates specific dependencies based on the content of the data, as opposed to its structure which can be verified on the schema level
- Parameters:
data – Data to validate
- Returns:
Return data if its valid
- Raises:
- property arguments: dict
Returns all the provider arguments and their JSON schema, keyed by argument name
- create_response(data: dict | None = None, response: Response = None, errors: list | None = None) Response[source]
Helper function to generate a
Responseobject- Parameters:
data – The data that was used to send the notification
response –
requests.Responseif existerrors – List of errors if relevant
- property defaults: dict
A dict of default provider values, taken from the default values declared on
schema_model
- property required: dict
Returns a dict with a
requiredkey, holding the list of arguments that must be passed. Fields listed in the model’srequired_with_default(required by the service but filled from a default) are included as well
- property schema: dict
The JSON schema of
schema_model, as generated by pydantic’smodel_json_schema(by_alias=True)- Returns:
JSON schema of the provider
- abstract property schema_model: type[SchemaModel]
The
SchemaModelsubclass that describes and validates the resource arguments
- class notifiers.core.Provider[source]
The Base class all notification providers inherit from.
- abstractmethod _send_notification(data: dict) Response[source]
The core method to trigger the provider notification. Must be overridden.
- Parameters:
data – Notification data
- notify(raise_on_errors: bool = False, **kwargs) Response[source]
The main method to send notifications. Prepares the data via the
_prepare_data()method and then sends the notification via the_send_notification()method- Parameters:
kwargs – Notification data
raise_on_errors – Should the
raise_on_errors()be invoked immediately
- Returns:
A
Responseobject- Raises:
NotificationErrorifraise_on_errorsis set to True and response contained errors
- property resources: list
Return a list of names of relevant
ProviderResourceobjects
- class notifiers.core.ProviderResource[source]
The base class that is used to fetch provider related resources like rooms, channels, users etc.
- class notifiers.core.Response(status: str, provider: str, data: dict, response: Response = None, errors: list | None = None)[source]
A wrapper for the Notification response.
- Parameters:
status – Response status string.
SUCCESSorFAILEDprovider – Provider name that returned that response. Correlates to
namedata – The notification data that was used for the notification
response – The response object that was returned. Usually
requests.Responseerrors – Holds a list of errors if relevant
- raise_on_errors()[source]
Raises a
NotificationErrorif response hold errors- Raises:
NotificationError: If response has errors
- notifiers.core.get_notifier(provider_name: str, strict: bool = False) Provider[source]
Convenience method to return an instantiated
Providerobject according to itname- Parameters:
provider_name – The
nameof the requestedProviderstrict – Raises a
ValueErrorif the given provider string was not found
- Returns:
Provideror None- Raises:
ValueError – In case
strictis True and provider not found
- notifiers.core.get_all_providers() dict[source]
Get all providers from the entry points and the default providers.
- Returns:
Dict: A dictionary containing the entry point names as keys and their corresponding values as values.
- notifiers.core.load_provider_from_points(entry_points: str) Provider[source]
Load a Provider class from a given entry point string.
This function takes an entry point string in the format ‘module_path:class_name’ and dynamically imports the specified Provider class. It performs validation to ensure the loaded class is a valid Provider.
- Parameters:
entry_points – A string in the format ‘module_path:class_name’ (e.g. ‘myapp.providers:EmailProvider’)
- Returns:
ProviderThe loaded Provider class- Raises:
ValueError – If the entry_points string format is invalid
ImportError – If the specified module cannot be imported
AttributeError – If the specified class cannot be found in the module
TypeError – If the loaded class is not a subclass of Provider
- Example:
>>> entry_points = "myapp.providers:EmailProvider" >>> provider_class = load_provider_from_points(entry_points) >>> provider = provider_class()
- notifiers.core.get_providers_from_entry_points(group_name: str = 'notifiers') dict[source]
Get a dictionary of plugins from the entry points based on the given group name.
This function will search for the entry points with the specified group name and return a dictionary where the keys are the names of the entry points and the values are the corresponding entry point values.
- Parameters:
group_name – The group name of the entry points to search for.
- Returns:
Dict: A dictionary containing the entry point names as keys and their corresponding values as values.
- Example:
>>> get_providers_from_entry_points("notifiers") {"plugin1": "package.module:PluginClass", "plugin2": "package2.module:OtherPluginClass"}
- notifiers.core.notify(provider_name: str, **kwargs) Response[source]
Quickly sends a notification without needing to get a notifier via the
get_notifier()method.- Parameters:
provider_name – Name of the notifier to use. Note that if this notifier name does not exist it will raise a
kwargs – Notification data, dependant on provider
- Returns:
- Raises:
NoSuchNotifierErrorIfprovider_nameis unknown, will raise notification error
Logging
- class notifiers.logging.NotificationHandler(provider: str, defaults: dict | None = None, **kwargs)[source]
A
logging.Handlerthat enables directly sending log messages to notifiers- emit(record)[source]
Override the
emit()method that takes themsgattribute from the log record passed- Parameters:
record –
logging.LogRecord
- handleError(record)[source]
Handles any errors raised during the
emit()method. Will only try to pass exceptions to fallback notifier (if defined) in case the exception is a sub-class ofNotifierException- Parameters:
record –
logging.LogRecord
- init_providers(provider, kwargs)[source]
Inits main and fallback provider if relevant
- Parameters:
provider – Provider name to use
kwargs – Additional kwargs
- Raises:
ValueError – If provider name or fallback names are not valid providers, a
ValueErrorwill be raised