PluginController Model
- class smarter.apps.plugin.manifest.controller.PluginController(user_profile, manifest=None, plugin_meta=None, name=None, **kwargs)[source]
Bases:
AbstractControllerProvides a unified interface for mapping between Pydantic manifest models, plugin implementations,.
and Django ORM models within the Smarter platform.
The PluginController is responsible for orchestrating the instantiation and management of plugin objects based on manifest data, plugin metadata, or plugin names. It supports dynamic loading of plugin classes, validation of manifest kinds, and ensures that only valid plugin configurations are accepted. This controller acts as a bridge between the declarative plugin manifests (often defined in YAML or JSON), the underlying plugin Python classes, and the persistent plugin metadata stored in the database.
Key Responsibilities
Validates and processes plugin manifest data, ensuring compatibility with supported plugin kinds.
Dynamically selects and instantiates the appropriate plugin class (API, SQL, or Static) based on manifest or metadata.
Maintains references to the manifest, plugin instance, and plugin metadata for coordinated access.
Integrates with user and account context to support multi-tenant plugin management.
Provides error handling for invalid or ambiguous plugin initialization scenarios.
Model Relationships
Utilizes
smarter.apps.plugin.models.PluginMetafor persistent plugin metadata.Interacts with Pydantic manifest models such as
smarter.apps.plugin.manifest.models.api_plugin.model.SAMApiPlugin,smarter.apps.plugin.manifest.models.sql_plugin.model.SAMSqlPlugin, andsmarter.apps.plugin.manifest.models.static_plugin.model.SAMStaticPlugin.Supports plugin implementations including
smarter.apps.plugin.plugin.api.ApiPlugin,smarter.apps.plugin.plugin.sql.SqlPlugin, andsmarter.apps.plugin.plugin.static.StaticPlugin.
Usage Example
# Initialize a PluginController with manifest data my_user_profile = UserProfile.get_cached_object(user=admin_user) controller = PluginController( manifest=my_manifest, user_profile=my_user_profile ) plugin_instance = controller.plugin # Initialize with plugin metadata my_plugin_meta = PluginMeta.objects.get(id=plugin_id) controller = PluginController( plugin_meta=my_plugin_meta, user_profile=my_user_profile ) plugin_instance = controller.plugin
Notes
Only one of manifest, plugin_meta, or name should be provided during initialization.
The controller enforces validation of manifest kinds and plugin class compatibility.
Logging and error handling are integrated using the Smarter platform’s logging and exception infrastructure.
- property account: Account | None
Returns the account for the current user.
Handle lazy instantiation from user or user_profile.
- Returns:
The account for the current user.
- Return type:
Account or None
- property account_number: str | None
A helper function to get the account number from the account.
- Returns:
The account number for the current account.
- Return type:
str or None
- property am_ready: bool
Returns True if the AccountMixin is am_ready to be used.
This is a convenience property that checks if the account and user are initialized. AccountMixin is considered am_ready if: - self.user is an instance of User - self.user_profile is an instance of UserProfile - self.account is an instance of Account
- Returns:
True if the AccountMixin is am_ready to be used.
- Return type:
- authenticate(api_token)
Authenticate the user using the provided API token.
The api_token will have been generated by the SmarterTokenAuthentication class and passed by the caller in the Authorization header of the request.
Example
Authorization: Token <api_token>
- bool_environment_variable(var_name, default=False)
Retrieves a boolean value from an environment variable.
This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.
- data_to_dict(data)
Converts data to a dictionary, handling different types of input.
This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.
- deserves_amnesty(slug)
Determines if a given URL deserves amnesty based on the amnesty URLs list.
This excuses certain endpoints (like health checks) from select middleware checks.
- dict_is_contained_in(dict1, dict2)
Checks if one dictionary is contained within another.
This method determines if all key-value pairs in dict1 are present in dict2.
- dict_is_subset(small, big)
Checks if one dictionary is a subset of another.
This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.
- property formatted_class_name: str
Returns the class name in a formatted string.
along with the name of this mixin.
- formatted_json(json_obj)
Formats a JSON object as a pretty-printed string with ANSI color codes for logging.
- property formatted_state_not_ready: str
Returns the not-ready state formatted for logging.
- Returns:
The formatted not-ready state as a string.
- Return type:
- property formatted_state_ready: str
Returns the readiness state formatted for logging.
- Returns:
The formatted readiness state as a string.
- Return type:
- formatted_text(text, color_code='\\x1b[1;31m')
Formats text with ANSI color codes for logging.
- formatted_text_blue(text)
Formats text in bold dark blue for logging.
- formatted_text_green(text)
Formats text in bright green for logging.
- formatted_text_red(text)
Formats text in dark red for logging.
- generate_fernet_encryption_key()
Generates a Fernet encryption key.
This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.
- Returns:
A new Fernet encryption key.
- Return type:
- get_readonly_csv_file(file_path)
Retrieves a read-only file object for a CSV file.
This method opens the specified CSV file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the CSV file to open.- Returns:
A read-only file object for the specified CSV file.
- Return type:
file
- get_readonly_yaml_file(file_path)
Retrieves a read-only file object for a YAML file.
This method opens the specified YAML file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the YAML file to open.- Returns:
A read-only file object for the specified YAML file.
- Return type:
file
- property health_check_urls: list[str]
Returns a list of URL paths that are considered health check endpoints.
- init(*args, **kwargs)
An optional method that can be called after initialization to perform any additional setup.
This is separate from __init__ to allow for more flexible initialization patterns.
- Parameters:
args – Positional arguments passed to the init method.
kwargs – Keyword arguments passed to the init method.
- Return type:
- Returns:
None
- property is_authenticated: bool
Returns True if the user is authenticated and is associated with an Account.
- log_ready_status()
Logs the ready status of the view.
- property manifest: SAMPluginCommon | None
- mask_string(string='', mask_char='*', mask_length=4, string_length=8)
Masks a string for secure logging.
This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.
- property obj: StaticPlugin | SqlPlugin | ApiPlugin | None
- property plugin: StaticPlugin | SqlPlugin | ApiPlugin | None
- property plugin_meta: PluginMeta | None
- property plugin_meta_class_map: Dict[str, type[ApiPlugin] | type[SqlPlugin] | type[StaticPlugin]][source]
- property ready: bool
Indicates whether the object is ready for use.
This is a placeholder that should be overridden in subclasses.
- Returns:
True if ready, False otherwise.
- Return type:
- recursive_sort_dict(data)
Recursively sorts a dictionary by its keys.
This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.
- rfc1034_compliant_str(name)
Converts a string to an RFC 1034 compliant format.
This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.
- rfc1034_compliant_to_snake(name)
Converts an RFC 1034 compliant string to snake_case.
This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.
- property sam_map: Dict[str, type[SAMApiPlugin] | type[SAMSqlPlugin] | type[SAMStaticPlugin]][source]
Maps manifest kinds to their respective SAM plugin classes.
- setup(*args, **kwargs)
This method is called by Django views during initialization.
It attempts to resolve the account and user information from the request object if it hasn’t already been set.
- Parameters:
args – Positional arguments passed to the view.
kwargs – Keyword arguments passed to the view, may include ‘request’.
- Returns:
The result of the superclass setup method.
- Return type:
- smarter_build_absolute_uri(request)
Attempts to get the absolute URI from a request object.
This utility function tries to retrieve the request URL from any valid child class of
django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implementbuild_absolute_uri().- Parameters:
request (
HttpRequest) – The request object.- Returns:
The absolute request URL.
- Return type:
- Raises:
SmarterValueError – If the URI cannot be built from the request.
- sorted_dict(data)
Returns a new dictionary with keys sorted.
- to_camel_case(data, convert_values=False)
Converts a snake_case string to camelCase.
This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.
- to_json()
Returns a JSON representation of the account, user, and user_profile.
- to_snake_case(data, convert_values=False)
Converts a camelCase or PascalCase string to snake_case.
This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.
- property unformatted_class_name: str
Returns the raw class name without formatting.
- Returns:
The unformatted class name as a string.
- Return type:
This is useful for logging or serialization where the plain class name is needed.
- property user: AnonymousUser | User | None
Returns the user.
Handle lazy instantiation from user_profile or account.
- Returns:
The user.
- Return type:
User or None
- property user_profile: UserProfile | None
Returns the user_profile for the current user.
Handle lazy instantiation from user or account.
- Returns:
The user_profile for the current user.
- Return type:
UserProfile or None