code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_delete_without_pricing(self): """Test that we can delete a part which does not have pricing information.""" pricing = self.part.pricing self.assertIsNone(pricing.pk) self.part.active = False self.part.save() self.part.delete() # Check that part was ac...
Test that we can delete a part which does not have pricing information.
test_delete_without_pricing
python
inventree/InvenTree
src/backend/InvenTree/part/test_pricing.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/test_pricing.py
MIT
def test_check_missing_pricing(self): """Tests for check_missing_pricing background task. Calling the check_missing_pricing task should: - Create PartPricing objects where there are none - Schedule pricing calculations for the newly created PartPricing objects """ from p...
Tests for check_missing_pricing background task. Calling the check_missing_pricing task should: - Create PartPricing objects where there are none - Schedule pricing calculations for the newly created PartPricing objects
test_check_missing_pricing
python
inventree/InvenTree
src/backend/InvenTree/part/test_pricing.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/test_pricing.py
MIT
def test_delete_part_with_stock_items(self): """Test deleting a part instance with stock items. This is to test a specific edge condition which was discovered that caused an IntegrityError. Ref: https://github.com/inventree/InvenTree/issues/4419 Essentially a series of on_delete listen...
Test deleting a part instance with stock items. This is to test a specific edge condition which was discovered that caused an IntegrityError. Ref: https://github.com/inventree/InvenTree/issues/4419 Essentially a series of on_delete listeners caused a new PartPricing object to be created, ...
test_delete_part_with_stock_items
python
inventree/InvenTree
src/backend/InvenTree/part/test_pricing.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/test_pricing.py
MIT
def test_multi_level_bom(self): """Test that pricing for multi-level BOMs is calculated correctly.""" # Create some parts A1 = part.models.Part.objects.create( name='A1', description='A1', assembly=True, component=True ) B1 = part.models.Part.objects.create( ...
Test that pricing for multi-level BOMs is calculated correctly.
test_multi_level_bom
python
inventree/InvenTree
src/backend/InvenTree/part/test_pricing.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/test_pricing.py
MIT
def attach_file(instance, filename): # pragma: no cover """ Generate a filename for the uploaded attachment. 2021-11-17 - This was moved here from part.models.py, as the function itself is no longer used, but is still required for migration """ # Construct a path to store a file attachmen...
Generate a filename for the uploaded attachment. 2021-11-17 - This was moved here from part.models.py, as the function itself is no longer used, but is still required for migration
attach_file
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0001_initial.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0001_initial.py
MIT
def update_pathstring(apps, schema_editor): """Construct pathstring for all existing PartCategory objects""" PartCategory = apps.get_model('part', 'partcategory') n = PartCategory.objects.count() if n > 0: for cat in PartCategory.objects.all(): # Construct complete path for cate...
Construct pathstring for all existing PartCategory objects
update_pathstring
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0083_auto_20220731_2357.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0083_auto_20220731_2357.py
MIT
def update_template_units(apps, schema_editor): """Update the units for each parameter template: - Check if the units are valid - Attempt to convert to valid units (if possible) """ PartParameterTemplate = apps.get_model('part', 'PartParameterTemplate') n_templates = PartParameterTemplate.obj...
Update the units for each parameter template: - Check if the units are valid - Attempt to convert to valid units (if possible)
update_template_units
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
MIT
def convert_to_numeric_value(value: str, units: str): """Convert a value (with units) to a numeric value. Defaults to zero if the value cannot be converted. """ # Default value is null result = None if units: try: result = InvenTree.conversion.convert_physical_value(value,...
Convert a value (with units) to a numeric value. Defaults to zero if the value cannot be converted.
convert_to_numeric_value
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
MIT
def update_parameter_values(apps, schema_editor): """Update the parameter values for all parts: - Calculate the 'data_numeric' value for each parameter - If the template has invalid units, we'll ignore """ PartParameter = apps.get_model('part', 'PartParameter') n_params = PartParameter.object...
Update the parameter values for all parts: - Calculate the 'data_numeric' value for each parameter - If the template has invalid units, we'll ignore
update_parameter_values
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0109_auto_20230517_1048.py
MIT
def migrate_part_units(apps, schema_editor): """Update the units field for each Part object: - Check if the units are valid - Attempt to convert to valid units (if possible) """ Part = apps.get_model('part', 'Part') parts = Part.objects.exclude(units=None).exclude(units='') n_parts = part...
Update the units field for each Part object: - Check if the units are valid - Attempt to convert to valid units (if possible)
migrate_part_units
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0111_auto_20230521_1350.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0111_auto_20230521_1350.py
MIT
def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None: """Forwards migration *attempts* to remove existing fields, but will fail gracefully if they do not exist""" try: super().database_forwards(app_label, schema_editor, from_state, to_state) print(...
Forwards migration *attempts* to remove existing fields, but will fail gracefully if they do not exist
database_forwards
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0112_auto_20230525_1606.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0112_auto_20230525_1606.py
MIT
def migrate_part_responsible_owner(apps, schema_editor): """Copy existing part.responsible field to part.responsible_owner""" Owner = apps.get_model('users', 'Owner') Part = apps.get_model('part', 'Part') User = apps.get_model('auth', 'user') ContentType = apps.get_model('contenttypes', 'contenttyp...
Copy existing part.responsible field to part.responsible_owner
migrate_part_responsible_owner
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0116_auto_20231023_0332.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0116_auto_20231023_0332.py
MIT
def reverse_owner_migration(apps, schema_editor): """Reverse the owner migration: - Set the 'responsible' field to a selected user - Only where 'responsible_owner' is set - Only where 'responsible_owner' is a User object """ Part = apps.get_model('part', 'Part') User = apps.get_model('auth...
Reverse the owner migration: - Set the 'responsible' field to a selected user - Only where 'responsible_owner' is set - Only where 'responsible_owner' is a User object
reverse_owner_migration
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0116_auto_20231023_0332.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0116_auto_20231023_0332.py
MIT
def set_key(apps, schema_editor): """Create a 'key' value for existing PartTestTemplate objects.""" import InvenTree.helpers PartTestTemplate = apps.get_model('part', 'PartTestTemplate') for template in PartTestTemplate.objects.all(): template.key = InvenTree.helpers.generateTestKey(str(templ...
Create a 'key' value for existing PartTestTemplate objects.
set_key
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0121_auto_20240207_0344.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0121_auto_20240207_0344.py
MIT
def set_testable(apps, schema_editor): """Set the 'testable' status to True for certain parts. Prior to migration part.0128, the 'trackable' attribute was used to determine if parts could have tests associated with them. However, 'trackable' comes with other restrictions (such as requiring a uniqu...
Set the 'testable' status to True for certain parts. Prior to migration part.0128, the 'trackable' attribute was used to determine if parts could have tests associated with them. However, 'trackable' comes with other restrictions (such as requiring a unique serial number). So, we have added a new...
set_testable
python
inventree/InvenTree
src/backend/InvenTree/part/migrations/0129_auto_20240815_0214.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/part/migrations/0129_auto_20240815_0214.py
MIT
def plugin_update(queryset, new_status: bool): """General function for bulk changing plugins.""" apps_changed = False # Run through all plugins in the queryset as the save method needs to be overridden for plugin in queryset: if plugin.active is not new_status: plugin.active = new_s...
General function for bulk changing plugins.
plugin_update
python
inventree/InvenTree
src/backend/InvenTree/plugin/admin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/admin.py
MIT
def filter_mixin(self, queryset, name, value): """Filter by implement mixin. - A comma-separated list of mixin names can be provided. - Only plugins which implement all of the provided mixins will be returned. """ matches = [] mixins = [x.strip().lower() for x in value.s...
Filter by implement mixin. - A comma-separated list of mixin names can be provided. - Only plugins which implement all of the provided mixins will be returned.
filter_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def delete(self, request, *args, **kwargs): """Handle DELETE request for a PluginConfig instance. We only allow plugin deletion if the plugin is not active. """ cfg = self.get_object() if cfg.active: raise ValidationError({ 'detail': _('Plugin cannot...
Handle DELETE request for a PluginConfig instance. We only allow plugin deletion if the plugin is not active.
delete
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def get_object(self): """Returns the object for the view.""" if self.request.data.get('pk', None): return self.queryset.get(pk=self.request.data.get('pk')) return super().get_object()
Returns the object for the view.
get_object
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def check_plugin( plugin_slug: Optional[str], plugin_pk: Optional[int] ) -> InvenTreePlugin: """Check that a plugin for the provided slug exists and get the config. Args: plugin_slug (str): Slug for plugin. plugin_pk (int): Primary key for plugin. Raises: NotFound: If plugin is...
Check that a plugin for the provided slug exists and get the config. Args: plugin_slug (str): Slug for plugin. plugin_pk (int): Primary key for plugin. Raises: NotFound: If plugin is not installed NotFound: If plugin is not correctly registered NotFound: If plugin is no...
check_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def get(self, request, plugin): """Get all settings for a plugin config.""" # look up the plugin plugin = check_plugin(plugin, None) settings = getattr(plugin, 'settings', {}) settings_dict = PluginSetting.all_settings( settings_definition=settings, plugin=plugin.pl...
Get all settings for a plugin config.
get
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def get_object(self): """Lookup the plugin setting object, based on the URL. The URL provides the 'slug' of the plugin, and the 'key' of the setting. Both the 'slug' and 'key' must be valid, else a 404 error is raised """ setting_key = self.kwargs['key'] # Look up plugi...
Lookup the plugin setting object, based on the URL. The URL provides the 'slug' of the plugin, and the 'key' of the setting. Both the 'slug' and 'key' must be valid, else a 404 error is raised
get_object
python
inventree/InvenTree
src/backend/InvenTree/plugin/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/api.py
MIT
def ready(self): """The ready method is extended to initialize plugins.""" if not isInMainThread() and not isInWorkerThread(): return if not canAppAccessDatabase( allow_test=True, allow_plugins=True, allow_shell=True ): logger.info('Skipping plugin lo...
The ready method is extended to initialize plugins.
ready
python
inventree/InvenTree
src/backend/InvenTree/plugin/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/apps.py
MIT
def __init__(self, path, message): """Init a plugin error. Args: path: Path on which the error occurred - used to find out which plugin it was message: The original error message """ self.path = path self.message = message
Init a plugin error. Args: path: Path on which the error occurred - used to find out which plugin it was message: The original error message
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/helpers.py
MIT
def handle_error(error, do_raise: bool = True, do_log: bool = True, log_name: str = ''): """Handles an error and casts it as an IntegrationPluginError.""" package_path = traceback.extract_tb(error.__traceback__)[-1].filename install_path = sysconfig.get_paths()['purelib'] try: package_name = pa...
Handles an error and casts it as an IntegrationPluginError.
handle_error
python
inventree/InvenTree
src/backend/InvenTree/plugin/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/helpers.py
MIT
def get_entrypoints(): """Returns list for entrypoints for InvenTree plugins.""" # on python before 3.12, we need to use importlib_metadata if sys.version_info < (3, 12): return entry_points().get('inventree_plugins', []) return entry_points(group='inventree_plugins')
Returns list for entrypoints for InvenTree plugins.
get_entrypoints
python
inventree/InvenTree
src/backend/InvenTree/plugin/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/helpers.py
MIT
def get_classes(module) -> list: """Get all classes in a given module.""" try: return inspect.getmembers(module, inspect.isclass) except Exception: log_error({module.__name__: 'Could not get classes'}, 'discovery') return []
Get all classes in a given module.
get_classes
python
inventree/InvenTree
src/backend/InvenTree/plugin/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/helpers.py
MIT
def get_plugins(pkg, baseclass, path=None): """Return a list of all modules under a given package. - Modules must be a subclass of the provided 'baseclass' - Modules must have a non-empty NAME parameter """ plugins = [] modules = get_modules(pkg, path=path) # Iterate through each module i...
Return a list of all modules under a given package. - Modules must be a subclass of the provided 'baseclass' - Modules must have a non-empty NAME parameter
get_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/helpers.py
MIT
def pip_command(*args): """Build and run a pip command using using the current python executable. Returns: The output of the pip command Raises: subprocess.CalledProcessError: If the pip command fails """ python = sys.executable command = [python, '-m', 'pip'] command.extend(args...
Build and run a pip command using using the current python executable. Returns: The output of the pip command Raises: subprocess.CalledProcessError: If the pip command fails
pip_command
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def handle_pip_error(error, path: str) -> list: """Raise a ValidationError when the pip command fails. - Log the error to the database - Format the output from a pip command into a list of error messages. - Raise an appropriate error """ log_error(path) output = error.output.decode('utf-8'...
Raise a ValidationError when the pip command fails. - Log the error to the database - Format the output from a pip command into a list of error messages. - Raise an appropriate error
handle_pip_error
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def get_install_info(packagename: str) -> dict: """Determine the install information for a particular package. - Uses 'pip show' to determine the install location of a package. """ logger.debug('get_install_info: %s', packagename) # Remove version information for c in '<>=!@ ': package...
Determine the install information for a particular package. - Uses 'pip show' to determine the install location of a package.
get_install_info
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def plugins_file_hash(): """Return the file hash for the plugins file.""" import hashlib pf = settings.PLUGIN_FILE if not pf or not pf.exists(): return None with pf.open('rb') as f: # Note: Once we support 3.11 as a minimum, we can use hashlib.file_digest return hashlib.sh...
Return the file hash for the plugins file.
plugins_file_hash
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def install_plugins_file(): """Install plugins from the plugins file.""" logger.info('Installing plugins from plugins file') pf = settings.PLUGIN_FILE if not pf or not pf.exists(): logger.warning('Plugin file %s does not exist', str(pf)) return cmd = ['install', '--disable-pip-ver...
Install plugins from the plugins file.
install_plugins_file
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def update_plugins_file(install_name, full_package=None, version=None, remove=False): """Add a plugin to the plugins file.""" if remove: logger.info('Removing plugin from plugins file: %s', install_name) else: logger.info('Adding plugin to plugins file: %s', install_name) # If a full pa...
Add a plugin to the plugins file.
update_plugins_file
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def install_plugin(url=None, packagename=None, user=None, version=None): """Install a plugin into the python virtual environment. Args: packagename: Optional package name to install url: Optional URL to install from user: Optional user performing the installation version: Option...
Install a plugin into the python virtual environment. Args: packagename: Optional package name to install url: Optional URL to install from user: Optional user performing the installation version: Optional version specifier
install_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def validate_package_plugin(cfg: plugin.models.PluginConfig, user=None): """Validate a package plugin for update or removal.""" if not cfg.plugin: raise ValidationError(_('Plugin was not found in registry')) if not cfg.is_package(): raise ValidationError(_('Plugin is not a packaged plugin')...
Validate a package plugin for update or removal.
validate_package_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def uninstall_plugin(cfg: plugin.models.PluginConfig, user=None, delete_config=True): """Uninstall a plugin from the python virtual environment. - The plugin must not be active - The plugin must be a "package" and have a valid package name Args: cfg: PluginConfig object user: User perf...
Uninstall a plugin from the python virtual environment. - The plugin must not be active - The plugin must be a "package" and have a valid package name Args: cfg: PluginConfig object user: User performing the uninstall delete_config: If True, delete the plugin configuration from the...
uninstall_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/installer.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/installer.py
MIT
def __init__(self, *args, **kwargs): """Override to set original state of the plugin-config instance.""" super().__init__(*args, **kwargs) self.__org_active = self.active # Append settings from registry plugin = registry.plugins_full.get(self.key, None) def get_plugin_m...
Override to set original state of the plugin-config instance.
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def get_plugin_meta(name): """Return a meta-value associated with this plugin.""" # Ignore if the plugin config is not defined if not plugin: return None # Ignore if the plugin is not active if not self.active: return None ...
Return a meta-value associated with this plugin.
get_plugin_meta
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def save(self, force_insert=False, force_update=False, *args, **kwargs): """Extend save method to reload plugins if the 'active' status changes.""" no_reload = kwargs.pop('no_reload', False) # check if no_reload flag is set super().save(force_insert, force_update, *args, **kwargs) if ...
Extend save method to reload plugins if the 'active' status changes.
save
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def is_builtin(self) -> bool: """Return True if this is a 'builtin' plugin.""" if not self.plugin: return False return self.plugin.check_is_builtin()
Return True if this is a 'builtin' plugin.
is_builtin
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def is_package(self) -> bool: """Return True if this is a 'package' plugin.""" if not self.plugin: return False return getattr(self.plugin, 'is_package', False)
Return True if this is a 'package' plugin.
is_package
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def admin_source(self) -> str: """Return the path to the javascript file which renders custom admin content for this plugin. - It is required that the file provides a 'renderPluginSettings' function! """ if not self.plugin: return None if not self.is_installed() or ...
Return the path to the javascript file which renders custom admin content for this plugin. - It is required that the file provides a 'renderPluginSettings' function!
admin_source
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def admin_context(self) -> dict: """Return the context data for the admin integration.""" if not self.plugin: return None if not self.is_installed() or not self.active: return None if hasattr(self.plugin, 'get_admin_context'): try: re...
Return the context data for the admin integration.
admin_context
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def activate(self, active: bool) -> None: """Set the 'active' status of this plugin instance.""" from InvenTree.tasks import check_for_migrations, offload_task if self.active == active: return self.active = active self.save() trigger_event(PluginEvents.PLUG...
Set the 'active' status of this plugin instance.
activate
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def get_setting_definition(cls, key, **kwargs): """In the BaseInvenTreeSetting class, we have a class attribute named 'SETTINGS', which is a dict object that fully defines all the setting parameters. Here, unlike the BaseInvenTreeSetting, we do not know the definitions of all settings 'ahead of...
In the BaseInvenTreeSetting class, we have a class attribute named 'SETTINGS', which is a dict object that fully defines all the setting parameters. Here, unlike the BaseInvenTreeSetting, we do not know the definitions of all settings 'ahead of time' (as they are defined externally in the plugins). ...
get_setting_definition
python
inventree/InvenTree
src/backend/InvenTree/plugin/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/models.py
MIT
def get_meta_value(self, key: str, old_key: Optional[str] = None, __default=None): """Reference a meta item with a key. Args: key (str): key for the value old_key (str, optional): deprecated key - will throw warning __default (optional): Value if nothing with key can...
Reference a meta item with a key. Args: key (str): key for the value old_key (str, optional): deprecated key - will throw warning __default (optional): Value if nothing with key can be found. Defaults to None. Returns: Value referenced with key, old_key ...
get_meta_value
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def plugin_slug(self): """Slug of plugin. If not set plugin name slugified """ slug = self.get_meta_value('SLUG', 'PLUGIN_SLUG', None) if not slug: slug = self.plugin_name() return slugify(slug.lower())
Slug of plugin. If not set plugin name slugified
plugin_slug
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def is_active(self): """Return True if this plugin is currently active.""" # Builtin plugins are always considered "active" if self.is_builtin: return True config = self.plugin_config() if config: return config.active return False # pragma: no c...
Return True if this plugin is currently active.
is_active
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def __init__(self, *args, **kwargs) -> None: """Init sup-parts. Adds state dicts. """ self._mixinreg = {} self._mixins = {} super().__init__(*args, **kwargs)
Init sup-parts. Adds state dicts.
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def mixin_enabled(self, key: str) -> bool: """Check if mixin is registered, enabled and ready.""" key = str(key).lower() if self.mixin(key): fnc_name = self._mixins.get(key) # Allow for simple case where the mixin is "always" ready if fnc_name is True: ...
Check if mixin is registered, enabled and ready.
mixin_enabled
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def add_mixin(self, key: str, fnc_enabled=True, cls=None): """Add a mixin to the plugins registry.""" key = str(key).lower() self._mixins[key] = fnc_enabled self.setup_mixin(key, cls=cls)
Add a mixin to the plugins registry.
add_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def setup_mixin(self, key, cls=None): """Define mixin details for the current mixin -> provides meta details for all active mixins.""" # get human name human_name = ( getattr(cls.MixinMeta, 'MIXIN_NAME', key) if cls and hasattr(cls, 'MixinMeta') else key ...
Define mixin details for the current mixin -> provides meta details for all active mixins.
setup_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def get_registered_mixins(self, with_base: bool = False, with_cls: bool = True): """Get all registered mixins for the plugin.""" mixins = getattr(self, '_mixinreg', None) if not mixins: return {} mixins = mixins.copy() # filter out base if not with_base and '...
Get all registered mixins for the plugin.
get_registered_mixins
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def check_version(self, latest=None) -> bool: """Check if plugin functions for the current InvenTree version.""" from InvenTree import version latest = latest if latest else version.inventreeVersionTuple() min_v = version.inventreeVersionTuple(self.MIN_VERSION) max_v = version.i...
Check if plugin functions for the current InvenTree version.
check_version
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def _get_value(self, meta_name: str, package_name: str) -> str: """Extract values from class meta or package info. Args: meta_name (str): Name of the class meta to use. package_name (str): Name of the package data to use. Returns: str: Extracted value, None ...
Extract values from class meta or package info. Args: meta_name (str): Name of the class meta to use. package_name (str): Name of the package data to use. Returns: str: Extracted value, None if nothing found.
_get_value
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def author(self): """Author of plugin - either from plugin settings or git.""" author = self._get_value('AUTHOR', 'author') if not author: author = _('No author found') # pragma: no cover return author
Author of plugin - either from plugin settings or git.
author
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def pub_date(self): """Publishing date of plugin - either from plugin settings or git.""" pub_date = getattr(self, 'PUBLISH_DATE', None) if not pub_date: pub_date = self.package.get('date') else: pub_date = datetime.fromisoformat(str(pub_date)) return pub...
Publishing date of plugin - either from plugin settings or git.
pub_date
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def settings_url(self) -> str: """URL to the settings panel for this plugin.""" if config := self.db: return InvenTree.helpers.pui_url(f'/settings/admin/plugin/{config.pk}/') return InvenTree.helpers.pui_url('/settings/admin/plugin/')
URL to the settings panel for this plugin.
settings_url
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def is_editable(cls): """Returns if the current part is editable.""" pkg_name = cls.__name__.split('.')[0] dist_info = list(Path(get_python_lib()).glob(f'{pkg_name}-*.dist-info')) return bool(len(dist_info) == 1)
Returns if the current part is editable.
is_editable
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def define_package(self): """Add package info of the plugin into plugins context.""" try: package = ( self._get_package_metadata() if self._is_package else self._get_package_commit() ) except TypeError: package =...
Add package info of the plugin into plugins context.
define_package
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def plugin_static_file(self, *args): """Construct a path to a static file within the plugin directory.""" import os from django.conf import settings url = os.path.join(settings.STATIC_URL, 'plugins', self.SLUG, *args) if not url.startswith('/'): url = '/' + url ...
Construct a path to a static file within the plugin directory.
plugin_static_file
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def get_admin_source(self) -> str: """Return a path to a JavaScript file which contains custom UI settings. The frontend code expects that this file provides a function named 'renderPluginSettings'. """ if not self.ADMIN_SOURCE: return None return self.plugin_static...
Return a path to a JavaScript file which contains custom UI settings. The frontend code expects that this file provides a function named 'renderPluginSettings'.
get_admin_source
python
inventree/InvenTree
src/backend/InvenTree/plugin/plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/plugin.py
MIT
def __init__(self) -> None: """Initialize registry. Set up all needed references for internal and external states. """ # plugin registry self.plugins: dict[str, InvenTreePlugin] = {} # List of active instances self.plugins_inactive: dict[ str, InvenTreePlugi...
Initialize registry. Set up all needed references for internal and external states.
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def get_plugin(self, slug, active=None, with_mixin=None): """Lookup plugin by slug (unique key). Args: slug (str): The slug of the plugin to look up. active (bool, optional): Filter by 'active' status of the plugin. If None, no filtering is applied. Defaults to None. ...
Lookup plugin by slug (unique key). Args: slug (str): The slug of the plugin to look up. active (bool, optional): Filter by 'active' status of the plugin. If None, no filtering is applied. Defaults to None. with_mixin (str, optional): Filter by mixin name. If None, no filter...
get_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def get_plugin_config(self, slug: str, name: Union[str, None] = None): """Return the matching PluginConfig instance for a given plugin. Args: slug: The plugin slug name: The plugin name (optional) """ import InvenTree.ready from plugin.models import Plugi...
Return the matching PluginConfig instance for a given plugin. Args: slug: The plugin slug name: The plugin name (optional)
get_plugin_config
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def set_plugin_state(self, slug, state): """Set the state(active/inactive) of a plugin. Args: slug (str): Plugin slug state (bool): Plugin state - true = active, false = inactive """ # Check if the registry needs to be reloaded self.check_reload() ...
Set the state(active/inactive) of a plugin. Args: slug (str): Plugin slug state (bool): Plugin state - true = active, false = inactive
set_plugin_state
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def call_plugin_function(self, slug: str, func: str, *args, **kwargs): """Call a member function (named by 'func') of the plugin named by 'slug'. As this is intended to be run by the background worker, we do not perform any try/except here. Instead, any error messages are returned to t...
Call a member function (named by 'func') of the plugin named by 'slug'. As this is intended to be run by the background worker, we do not perform any try/except here. Instead, any error messages are returned to the worker.
call_plugin_function
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def with_mixin( self, mixin: str, active: bool = True, builtin: Optional[bool] = None ) -> list: """Returns reference to all plugins that have a specified mixin enabled. Args: mixin (str): Mixin name active (bool, optional): Filter by 'active' status of plugin. Defau...
Returns reference to all plugins that have a specified mixin enabled. Args: mixin (str): Mixin name active (bool, optional): Filter by 'active' status of plugin. Defaults to True. builtin (bool, optional): Filter by 'builtin' status of plugin. Defaults to None.
with_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _load_plugins( self, full_reload: bool = False, _internal: Optional[list] = None ): """Load and activate all IntegrationPlugins. Args: full_reload (bool, optional): Reload everything - including plugin mechanism. Defaults to False. _internal (list, optional): Int...
Load and activate all IntegrationPlugins. Args: full_reload (bool, optional): Reload everything - including plugin mechanism. Defaults to False. _internal (list, optional): Internal apps to reload (used for testing). Defaults to None
_load_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _unload_plugins(self, force_reload: bool = False): """Unload and deactivate all IntegrationPlugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. """ logger.info('Start unloading plugins') # remove all plugins from registry ...
Unload and deactivate all IntegrationPlugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False.
_unload_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def reload_plugins( self, full_reload: bool = False, force_reload: bool = False, collect: bool = False, _internal: Optional[list] = None, ): """Reload the plugin registry. This should be considered the single point of entry for loading plugins! Args:...
Reload the plugin registry. This should be considered the single point of entry for loading plugins! Args: full_reload (bool, optional): Reload everything - including plugin mechanism. Defaults to False. force_reload (bool, optional): Also reload base apps. Defaults to False. ...
reload_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def plugin_dirs(self): """Construct a list of directories from where plugins can be loaded.""" # Builtin plugins are *always* loaded dirs = ['plugin.builtin'] if settings.PLUGINS_ENABLED: # Any 'external' plugins are only loaded if PLUGINS_ENABLED is set to True ...
Construct a list of directories from where plugins can be loaded.
plugin_dirs
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def collect_plugins(self): """Collect plugins from all possible ways of loading. Returned as list.""" collected_plugins = [] # Collect plugins from paths for plugin_dir in self.plugin_dirs(): logger.debug("Loading plugins from directory '%s'", plugin_dir) parent...
Collect plugins from all possible ways of loading. Returned as list.
collect_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def discover_mixins(self): """Discover all mixins from plugins and register them.""" collected_mixins = {} for plg in self.plugins.values(): collected_mixins.update(plg.get_registered_mixins()) self.mixin_modules = collected_mixins
Discover all mixins from plugins and register them.
discover_mixins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def install_plugin_file(self): """Make sure all plugins are installed in the current environment.""" from plugin.installer import install_plugins_file, plugins_file_hash file_hash = plugins_file_hash() if file_hash != settings.PLUGIN_FILE_HASH: install_plugins_file() ...
Make sure all plugins are installed in the current environment.
install_plugin_file
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _init_plugin(self, plugin, configs: dict): """Initialise a single plugin. Args: plugin: Plugin module configs: Plugin configuration dictionary force_reload (bool, optional): Force reload of plugin. Defaults to False. """ from InvenTree import vers...
Initialise a single plugin. Args: plugin: Plugin module configs: Plugin configuration dictionary force_reload (bool, optional): Force reload of plugin. Defaults to False.
_init_plugin
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _init_plugins(self): """Initialise all found plugins. Args: disabled (str, optional): Loading path of disabled app. Defaults to None. Raises: error: IntegrationPluginError """ # Imports need to be in this level to prevent early db model imports ...
Initialise all found plugins. Args: disabled (str, optional): Loading path of disabled app. Defaults to None. Raises: error: IntegrationPluginError
_init_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def __get_mixin_order(self): """Returns a list of mixin classes, in the order that they should be activated.""" # Preset list of mixins order = self.DEFAULT_MIXIN_ORDER # Append mixins that are not defined in the default list order += [ m.get('cls') for m...
Returns a list of mixin classes, in the order that they should be activated.
__get_mixin_order
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _activate_plugins( self, force_reload=False, full_reload: bool = False, _internal: Optional[list] = None, ): """Run activation functions for all plugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. full_r...
Run activation functions for all plugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. full_reload (bool, optional): Reload everything - including plugin mechanism. Defaults to False.
_activate_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _deactivate_plugins(self, force_reload: bool = False): """Run deactivation functions for all plugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. """ for mixin in reversed(self.__get_mixin_order()): if hasattr(mixin, '_deact...
Run deactivation functions for all plugins. Args: force_reload (bool, optional): Also reload base apps. Defaults to False.
_deactivate_plugins
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _try_reload(self, cmd, *args, **kwargs): """Wrapper to try reloading the apps. Throws an custom error that gets handled by the loading function. """ try: cmd(*args, **kwargs) return True, [] except Exception as error: # pragma: no cover h...
Wrapper to try reloading the apps. Throws an custom error that gets handled by the loading function.
_try_reload
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _reload_apps( self, force_reload: bool = False, full_reload: bool = False, _internal: Optional[list] = None, ): """Internal: reload apps using django internal functions. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. ...
Internal: reload apps using django internal functions. Args: force_reload (bool, optional): Also reload base apps. Defaults to False. full_reload (bool, optional): Reload everything - including plugin mechanism. Defaults to False. _internal (list, optional): Internal use onl...
_reload_apps
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _update_urls(self): """Due to the order in which plugins are loaded, the patterns in urls.py may be out of date. This function updates the patterns in urls.py to ensure that the correct patterns are loaded, and then refreshes the django url cache. Note that we also have to refresh ...
Due to the order in which plugins are loaded, the patterns in urls.py may be out of date. This function updates the patterns in urls.py to ensure that the correct patterns are loaded, and then refreshes the django url cache. Note that we also have to refresh the admin site URLS, as any...
_update_urls
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def update_plugin_hash(self): """When the state of the plugin registry changes, update the hash.""" self.registry_hash = self.calculate_plugin_hash() try: old_hash = get_global_setting( '_PLUGIN_REGISTRY_HASH', '', create=False, cache=False ) exce...
When the state of the plugin registry changes, update the hash.
update_plugin_hash
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def plugin_settings_keys(self): """A list of keys which are used to store plugin settings.""" return [ 'ENABLE_PLUGINS_APP', 'ENABLE_PLUGINS_EVENTS', 'ENABLE_PLUGINS_INTERFACE', 'ENABLE_PLUGINS_NAVIGATION', 'ENABLE_PLUGINS_SCHEDULE', ...
A list of keys which are used to store plugin settings.
plugin_settings_keys
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def calculate_plugin_hash(self): """Calculate a 'hash' value for the current registry. This is used to detect changes in the plugin registry, and to inform other processes that the plugin registry has changed """ from hashlib import md5 data = md5() # Hash for ...
Calculate a 'hash' value for the current registry. This is used to detect changes in the plugin registry, and to inform other processes that the plugin registry has changed
calculate_plugin_hash
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def check_reload(self): """Determine if the registry needs to be reloaded. Returns True if the registry has changed and was reloaded. """ if settings.TESTING and not settings.PLUGIN_TESTING_RELOAD: # Skip if running during unit testing return False if no...
Determine if the registry needs to be reloaded. Returns True if the registry has changed and was reloaded.
check_reload
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def _load_source(modname, filename): """Helper function to replace deprecated & removed imp.load_source. See https://docs.python.org/3/whatsnew/3.12.html#imp """ if modname in sys.modules: del sys.modules[modname] # loader = importlib.machinery.SourceFileLoader(modname, filename) spec ...
Helper function to replace deprecated & removed imp.load_source. See https://docs.python.org/3/whatsnew/3.12.html#imp
_load_source
python
inventree/InvenTree
src/backend/InvenTree/plugin/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/registry.py
MIT
def update(self, instance, data): """Perform update on the metadata field. Rules: - If this is a partial (PATCH) update, try to 'merge' data in - Else, if it is a PUT update, overwrite any existing metadata """ if self.partial: # Default behavior is to "merge...
Perform update on the metadata field. Rules: - If this is a partial (PATCH) update, try to 'merge' data in - Else, if it is a PUT update, overwrite any existing metadata
update
python
inventree/InvenTree
src/backend/InvenTree/plugin/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/serializers.py
MIT
def validate(self, data): """Validate inputs. Make sure both confirm and url are provided. """ super().validate(data) # check the base requirements are met if not data.get('confirm'): raise ValidationError({'confirm': _('Installation not confirmed')}) ...
Validate inputs. Make sure both confirm and url are provided.
validate
python
inventree/InvenTree
src/backend/InvenTree/plugin/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/serializers.py
MIT
def save(self): """Install a plugin from a package registry and set operational results as instance data.""" from plugin.installer import install_plugin data = self.validated_data packagename = data.get('packagename', '') url = data.get('url', '') version = data.get('ve...
Install a plugin from a package registry and set operational results as instance data.
save
python
inventree/InvenTree
src/backend/InvenTree/plugin/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/serializers.py
MIT
def __init__(self, **kwargs): """Custom init routine for the serializer.""" kwargs['pk_field'] = 'key' kwargs['queryset'] = PluginConfig.objects.all() super().__init__(**kwargs)
Custom init routine for the serializer.
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/serializers.py
MIT
def clear_static_dir(path, recursive=True): """Clear the specified directory from the 'static' output directory. Arguments: path: The path to the directory to clear recursive: If True, clear the directory recursively """ if not staticfiles_storage.exists(path): return dirs,...
Clear the specified directory from the 'static' output directory. Arguments: path: The path to the directory to clear recursive: If True, clear the directory recursively
clear_static_dir
python
inventree/InvenTree
src/backend/InvenTree/plugin/staticfiles.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/staticfiles.py
MIT
def collect_plugins_static_files(): """Copy static files from all installed plugins into the static directory.""" registry.check_reload() logger.info('Collecting static files for all installed plugins.') for slug in registry.plugins: copy_plugin_static_files(slug, check_reload=False)
Copy static files from all installed plugins into the static directory.
collect_plugins_static_files
python
inventree/InvenTree
src/backend/InvenTree/plugin/staticfiles.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/staticfiles.py
MIT
def clear_plugins_static_files(): """Clear out static files for plugins which are no longer active.""" installed_plugins = set(registry.plugins.keys()) path = 'plugins/' # Check that the directory actually exists if not staticfiles_storage.exists(path): return # Get all static files i...
Clear out static files for plugins which are no longer active.
clear_plugins_static_files
python
inventree/InvenTree
src/backend/InvenTree/plugin/staticfiles.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/staticfiles.py
MIT
def copy_plugin_static_files(slug, check_reload=True): """Copy static files for the specified plugin.""" if check_reload: registry.check_reload() plugin = registry.get_plugin(slug) if not plugin: return logger.info("Collecting static files for plugin '%s'", slug) # Get the so...
Copy static files for the specified plugin.
copy_plugin_static_files
python
inventree/InvenTree
src/backend/InvenTree/plugin/staticfiles.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/staticfiles.py
MIT
def get_dirs(self): """Returns all template dir paths in plugins.""" dirname = 'templates' template_dirs = [] for plugin in registry.plugins.values(): new_path = plugin.path().joinpath(dirname) if new_path.is_dir(): template_dirs.append(new_path) ...
Returns all template dir paths in plugins.
get_dirs
python
inventree/InvenTree
src/backend/InvenTree/plugin/template.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/template.py
MIT
def test_plugin_settings(self): """Test plugin settings access via the API.""" # Ensure we have superuser permissions self.user.is_superuser = True self.user.save() # Activate the 'sample' plugin via the API cfg = PluginConfig.objects.filter(key='sample').first() ...
Test plugin settings access via the API.
test_plugin_settings
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_api.py
MIT
def test_tag_mixin_enabled(self): """Check that mixin enabled functions work.""" key = 'urls' # mixin enabled self.assertEqual(plugin_tags.mixin_enabled(self.sample, key), True) # mixin not enabled self.assertEqual(plugin_tags.mixin_enabled(self.plugin_wrong, key), False)...
Check that mixin enabled functions work.
test_tag_mixin_enabled
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT