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 __ne__(self, obj): """Override inequality operator to allow comparison with int.""" if type(self) is type(obj): return super().__ne__(obj) return self.value != obj
Override inequality operator to allow comparison with int.
__ne__
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def _is_element(cls, d): """Check if the supplied value is a valid status code.""" if d.startswith('_'): return False if d != d.upper(): return False value = getattr(cls, d, None) if value is None: return False if callable(value): ...
Check if the supplied value is a valid status code.
_is_element
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def custom_queryset(cls): """Return a queryset of all custom values for this status class.""" from common.models import InvenTreeCustomUserStateModel try: return InvenTreeCustomUserStateModel.objects.filter( reference_status=cls.__name__ ) except ...
Return a queryset of all custom values for this status class.
custom_queryset
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def custom_values(cls): """Return all user-defined custom values for this status class.""" if query := cls.custom_queryset(): return list(query) return []
Return all user-defined custom values for this status class.
custom_values
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def values(cls, key=None): """Return a dict representation containing all required information.""" elements = [itm for itm in cls if cls._is_element(itm.name)] if key is None: return elements ret = [itm for itm in elements if itm.value == key] if ret: re...
Return a dict representation containing all required information.
values
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def render(cls, key, large=False): """Render the value as a HTML label.""" # If the key cannot be found, pass it back item = cls.values(key) if item is None: return key return f"<span class='badge rounded-pill bg-{item.color}'>{item.label}</span>"
Render the value as a HTML label.
render
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def tag(cls): """Return tag for this status code.""" # Return the tag if it is defined if hasattr(cls, '_TAG') and bool(cls._TAG): return cls._TAG.value # Try to find a default tag # Remove `Status` from the class name ref_name = cls.__name__.removesuffix('St...
Return tag for this status code.
tag
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def label(cls, key): """Return the status code label associated with the provided value.""" filtered = cls.values(key) if filtered is None: return key return filtered.label
Return the status code label associated with the provided value.
label
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def template_context(cls, custom=True): """Return a dict representation containing all required information for templates.""" data = cls.dict(custom=custom) ret = {x['name']: x['key'] for x in data.values()} ret['list'] = list(data.values()) return ret
Return a dict representation containing all required information for templates.
template_context
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def save(self, *args, **kwargs): """Custom save method for StatusCodeMixin. - Ensure custom status code values are correctly updated """ if self.status_class: # Check that the current 'logical key' actually matches the current status code custom_values = self.sta...
Custom save method for StatusCodeMixin. - Ensure custom status code values are correctly updated
save
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def set_status(self, status: int) -> bool: """Set the status code for this object.""" if not self.status_class: raise NotImplementedError('Status class not defined') base_values = self.status_class.values() custom_value_set = self.status_class.custom_values() custom...
Set the status code for this object.
set_status
python
inventree/InvenTree
src/backend/InvenTree/generic/states/states.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/states.py
MIT
def test_code_definition(self): """Test that the status code class has been defined correctly.""" self.assertEqual(GeneralStatus.PENDING, 10) self.assertEqual(GeneralStatus.PLACED, 20) self.assertEqual(GeneralStatus.COMPLETE, 30)
Test that the status code class has been defined correctly.
test_code_definition
python
inventree/InvenTree
src/backend/InvenTree/generic/states/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/tests.py
MIT
def test_code_functions(self): """Test that the status code class functions work correctly.""" # render self.assertEqual( GeneralStatus.render(10), "<span class='badge rounded-pill bg-secondary'>Pending</span>", ) self.assertEqual( GeneralStatu...
Test that the status code class functions work correctly.
test_code_functions
python
inventree/InvenTree
src/backend/InvenTree/generic/states/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/tests.py
MIT
def test_color(self): """Test that the color enum validation works.""" with self.assertRaises(ValueError) as e: class TTTT(StatusCode): PENDING = 10, _('Pending'), 'invalid' self.assertEqual( str(e.exception), "Invalid color value 'invalid' for status 'P...
Test that the color enum validation works.
test_color
python
inventree/InvenTree
src/backend/InvenTree/generic/states/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/tests.py
MIT
def test_tag_display_status_label(self): """Test that the display_status_label tag (mainly the same as status_label).""" from .tags import display_status_label self.assertEqual( display_status_label('general', 10, 11), "<span class='badge rounded-pill bg-secondary'>Pendi...
Test that the display_status_label tag (mainly the same as status_label).
test_tag_display_status_label
python
inventree/InvenTree
src/backend/InvenTree/generic/states/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/tests.py
MIT
def test_all_states(self): """Test the API endpoint for listing all status models.""" response = self.get(reverse('api-status-all')) # 10 built-in state classes, plus the added GeneralState class self.assertEqual(len(response.data), 12) # Test the BuildStatus model buil...
Test the API endpoint for listing all status models.
test_all_states
python
inventree/InvenTree
src/backend/InvenTree/generic/states/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/tests.py
MIT
def test_class(self): """Ensure that the class itself works.""" class ErrorImplementation(TransitionMethod): ... with self.assertRaises(NotImplementedError): ErrorImplementation() _clean_storage([ErrorImplementation])
Ensure that the class itself works.
test_class
python
inventree/InvenTree
src/backend/InvenTree/generic/states/test_transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/test_transition.py
MIT
def test_storage(self): """Ensure that the storage collection mechanism works.""" global raise_storage global raise_function raise_storage = True raise_function = False class RaisingImplementation(TransitionMethod): def transition(self, *args, **kwargs): ...
Ensure that the storage collection mechanism works.
test_storage
python
inventree/InvenTree
src/backend/InvenTree/generic/states/test_transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/test_transition.py
MIT
def test_function(self): """Ensure that a TransitionMethod's function is called.""" global raise_storage global raise_function raise_storage = False raise_function = True # Setup class ValidImplementationNoEffect(TransitionMethod): def transition(sel...
Ensure that a TransitionMethod's function is called.
test_function
python
inventree/InvenTree
src/backend/InvenTree/generic/states/test_transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/test_transition.py
MIT
def test_default_function(self): """Ensure that the default function is called.""" with self.assertRaises(MyPrivateError) as exp: StateTransitionMixin.handle_transition(0, 1, self, self, dflt) self.assertEqual(str(exp.exception), 'dflt')
Ensure that the default function is called.
test_default_function
python
inventree/InvenTree
src/backend/InvenTree/generic/states/test_transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/test_transition.py
MIT
def __init__(self) -> None: """Check that the method is defined correctly. This checks that: - The needed functions are implemented """ # Check if a sending fnc is defined if not hasattr(self, 'transition'): raise NotImplementedError( 'A Trans...
Check that the method is defined correctly. This checks that: - The needed functions are implemented
__init__
python
inventree/InvenTree
src/backend/InvenTree/generic/states/transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/transition.py
MIT
def collect(self): """Collect all classes in the environment that are transition methods.""" filtered_list = {} for item in InvenTree.helpers.inheritors(TransitionMethod): # Try if valid try: item() except NotImplementedError: c...
Collect all classes in the environment that are transition methods.
collect
python
inventree/InvenTree
src/backend/InvenTree/generic/states/transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/transition.py
MIT
def handle_transition( self, current_state, target_state, instance, default_action, **kwargs ): """Handle a state transition for an object. Args: current_state: Current state of instance target_state: Target state of instance instance: Object instance ...
Handle a state transition for an object. Args: current_state: Current state of instance target_state: Target state of instance instance: Object instance default_action: Default action to be taken if none of the transitions returns a boolean true value
handle_transition
python
inventree/InvenTree
src/backend/InvenTree/generic/states/transition.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/transition.py
MIT
def __call__(self, value): """Check that the provided status code is valid.""" if status_class := self.status_class: values = status_class.keys(custom=True) if value not in values: raise ValidationError(_('Invalid status code'))
Check that the provided status code is valid.
__call__
python
inventree/InvenTree
src/backend/InvenTree/generic/states/validators.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/generic/states/validators.py
MIT
def formfield_for_dbfield(self, db_field, request, **kwargs): """Override the choices for the column field.""" if db_field.name == 'column': # TODO: Implement this! queryset = self.get_queryset(request) if queryset.count() > 0: session = queryset.firs...
Override the choices for the column field.
formfield_for_dbfield
python
inventree/InvenTree
src/backend/InvenTree/importer/admin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/admin.py
MIT
def get_readonly_fields(self, request, obj=None): """Update the readonly fields for the admin interface.""" fields = ['columns', 'status', 'timestamp'] # Prevent data file from being edited after upload! if obj: fields += ['data_file'] else: fields += ['f...
Update the readonly fields for the admin interface.
get_readonly_fields
python
inventree/InvenTree
src/backend/InvenTree/importer/admin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/admin.py
MIT
def formfield_for_dbfield(self, db_field, request, **kwargs): """Override the choices for the model_type field.""" if db_field.name == 'model_type': db_field.choices = importer.registry.supported_model_options() return super().formfield_for_dbfield(db_field, request, **kwargs)
Override the choices for the model_type field.
formfield_for_dbfield
python
inventree/InvenTree
src/backend/InvenTree/importer/admin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/admin.py
MIT
def has_object_permission(self, request, view, obj): """Check if the user has permission to access the imported object.""" # For safe methods (GET, HEAD, OPTIONS), allow access if request.method in permissions.SAFE_METHODS: return True if isinstance(obj, importer.models.Data...
Check if the user has permission to access the imported object.
has_object_permission
python
inventree/InvenTree
src/backend/InvenTree/importer/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/api.py
MIT
def get(self, request): """Return a list of models available for import.""" models = [] for serializer in importer.registry.get_supported_serializers(): model = serializer.Meta.model url = model.get_api_url() if hasattr(model, 'get_api_url') else None models...
Return a list of models available for import.
get
python
inventree/InvenTree
src/backend/InvenTree/importer/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/api.py
MIT
def post(self, request, pk): """Accept the field mapping for a DataImportSession.""" session = get_object_or_404(importer.models.DataImportSession, pk=pk) # Check that the user has permission to accept the field mapping if model_class := session.model_class: if not check_use...
Accept the field mapping for a DataImportSession.
post
python
inventree/InvenTree
src/backend/InvenTree/importer/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/api.py
MIT
def get_serializer_context(self): """Add the import session object to the serializer context.""" ctx = super().get_serializer_context() try: ctx['session'] = importer.models.DataImportSession.objects.get( pk=self.kwargs.get('pk', None) ) except Ex...
Add the import session object to the serializer context.
get_serializer_context
python
inventree/InvenTree
src/backend/InvenTree/importer/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/api.py
MIT
def __init__(self, *args, **kwargs): """Initialise the DataImportSerializerMixin. Determine if the serializer is being used for data import, and if so, adjust the serializer fields accordingly. """ importing = kwargs.pop('importing', False) super().__init__(*args, **kwa...
Initialise the DataImportSerializerMixin. Determine if the serializer is being used for data import, and if so, adjust the serializer fields accordingly.
__init__
python
inventree/InvenTree
src/backend/InvenTree/importer/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/mixins.py
MIT
def get_importable_fields(self) -> dict: """Return a dict of fields which can be imported against this serializer instance. Returns: dict: A dictionary of field names and field objects """ importable_fields = {} if meta := getattr(self, 'Meta', None): re...
Return a dict of fields which can be imported against this serializer instance. Returns: dict: A dictionary of field names and field objects
get_importable_fields
python
inventree/InvenTree
src/backend/InvenTree/importer/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/mixins.py
MIT
def model_class(self): """Return the model class for this importer.""" serializer = self.serializer_class if serializer: return serializer.Meta.model
Return the model class for this importer.
model_class
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def serializer_class(self): """Return the serializer class for this importer.""" from importer.registry import supported_models return supported_models().get(self.model_type, None)
Return the serializer class for this importer.
serializer_class
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def extract_columns(self) -> None: """Run initial column extraction and mapping. This method is called when the import session is first created. - Extract column names from the data file - Create a default mapping for each field in the serializer - Find a default "backup" value...
Run initial column extraction and mapping. This method is called when the import session is first created. - Extract column names from the data file - Create a default mapping for each field in the serializer - Find a default "backup" value for each field (if one exists)
extract_columns
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def accept_mapping(self) -> None: """Accept current mapping configuration. - Validate that the current column mapping is correct - Trigger the data import process """ # First, we need to ensure that all the *required* columns have been mapped required_fields = self.requi...
Accept current mapping configuration. - Validate that the current column mapping is correct - Trigger the data import process
accept_mapping
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def trigger_data_import(self) -> None: """Trigger the data import process for this session. Offloads the task to the background worker process. """ from InvenTree.tasks import offload_task # Mark the import task status as "IMPORTING" self.status = DataImportStatusCode.I...
Trigger the data import process for this session. Offloads the task to the background worker process.
trigger_data_import
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def import_data(self) -> None: """Perform the data import process for this session.""" # Clear any existing data rows self.rows.all().delete() df = importer.operations.load_data_file(self.data_file) if df is None: # TODO: Log an error message against the import sess...
Perform the data import process for this session.
import_data
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def check_complete(self) -> bool: """Check if the import session is complete.""" if self.completed_row_count < self.row_count: return False # Update the status of this session if self.status != DataImportStatusCode.COMPLETE.value: self.status = DataImportStatusCo...
Check if the import session is complete.
check_complete
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def available_fields(self): """Returns information on the available fields. - This method is designed to be introspected by the frontend, for rendering the various fields. - We make use of the InvenTree.metadata module to provide extra information about the fields. Note that we cache t...
Returns information on the available fields. - This method is designed to be introspected by the frontend, for rendering the various fields. - We make use of the InvenTree.metadata module to provide extra information about the fields. Note that we cache these fields, as they are expensive to c...
available_fields
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def required_fields(self) -> dict: """Returns information on which fields are *required* for import.""" fields = self.available_fields() required = {} for field, info in fields.items(): if info.get('required', False): required[field] = info return r...
Returns information on which fields are *required* for import.
required_fields
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def validate_unique(self, exclude=None): """Ensure that the column mapping is unique within the session.""" super().validate_unique(exclude) columns = self.session.column_mappings.exclude(pk=self.pk) if ( self.column not in ['', None] and columns.filter(column=s...
Ensure that the column mapping is unique within the session.
validate_unique
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def available_fields(self): """Return a list of available fields for this import session. These fields get cached, as they are expensive to compute. """ if fields := getattr(self, '_available_fields', None): return fields self._available_fields = self.session.availa...
Return a list of available fields for this import session. These fields get cached, as they are expensive to compute.
available_fields
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def field_definition(self): """Return the field definition associated with this column mapping.""" fields = self.available_fields return fields.get(self.field, None)
Return the field definition associated with this column mapping.
field_definition
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def label(self): """Extract the 'label' associated with the mapped field.""" if field_def := self.field_definition: return field_def.get('label', None)
Extract the 'label' associated with the mapped field.
label
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def description(self): """Extract the 'description' associated with the mapped field.""" description = None if field_def := self.field_definition: description = field_def.get('help_text', None) if not description: description = self.label return descrip...
Extract the 'description' associated with the mapped field.
description
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def default_values(self) -> dict: """Return a dict object of the 'default' values for this row.""" defaults = self.session.field_defaults or {} if type(defaults) is not dict: try: defaults = json.loads(str(defaults)) except json.JSONDecodeError: ...
Return a dict object of the 'default' values for this row.
default_values
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def override_values(self) -> dict: """Return a dict object of the 'override' values for this row.""" overrides = self.session.field_overrides or {} if type(overrides) is not dict: try: overrides = json.loads(str(overrides)) except json.JSONDecodeError: ...
Return a dict object of the 'override' values for this row.
override_values
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def extract_data( self, available_fields: Optional[dict] = None, field_mapping: Optional[dict] = None, commit=True, ): """Extract row data from the provided data dictionary.""" if not field_mapping: field_mapping = self.session.field_mapping if no...
Extract row data from the provided data dictionary.
extract_data
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def serializer_data(self): """Construct data object to be sent to the serializer. - If available, we use the "default" values provided by the import session - If available, we use the "override" values provided by the import session """ data = {} data.update(self.defaul...
Construct data object to be sent to the serializer. - If available, we use the "default" values provided by the import session - If available, we use the "override" values provided by the import session
serializer_data
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def construct_serializer(self, request=None): """Construct a serializer object for this row.""" if serializer_class := self.session.serializer_class: return serializer_class( data=self.serializer_data(), context={'request': request} )
Construct a serializer object for this row.
construct_serializer
python
inventree/InvenTree
src/backend/InvenTree/importer/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/models.py
MIT
def load_data_file(data_file, file_format=None): """Load data file into a tablib dataset. Arguments: data_file: django file object containing data to import (should be already opened!) file_format: Format specifier for the data file """ # Introspect the file format based on the provided...
Load data file into a tablib dataset. Arguments: data_file: django file object containing data to import (should be already opened!) file_format: Format specifier for the data file
load_data_file
python
inventree/InvenTree
src/backend/InvenTree/importer/operations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/operations.py
MIT
def extract_column_names(data_file) -> list: """Extract column names from a data file. Uses the tablib library to extract column names from a data file. Args: data_file: File object containing data to import Returns: List of column names extracted from the file Raises: Va...
Extract column names from a data file. Uses the tablib library to extract column names from a data file. Args: data_file: File object containing data to import Returns: List of column names extracted from the file Raises: ValidationError: If the data file is not in a valid fo...
extract_column_names
python
inventree/InvenTree
src/backend/InvenTree/importer/operations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/operations.py
MIT
def get_field_label(field) -> str: """Return the label for a field in a serializer class. Check for labels in the following order of descending priority: - The serializer class has a 'label' specified for the field - The underlying model has a 'verbose_name' specified - The field name is used as t...
Return the label for a field in a serializer class. Check for labels in the following order of descending priority: - The serializer class has a 'label' specified for the field - The underlying model has a 'verbose_name' specified - The field name is used as the label Arguments: field: Fi...
get_field_label
python
inventree/InvenTree
src/backend/InvenTree/importer/operations.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/operations.py
MIT
def register(self, serializer) -> None: """Register a new serializer with the importer registry.""" if not issubclass(serializer, DataImportSerializerMixin): logger.debug('Invalid serializer class: %s', type(serializer)) return if not issubclass(serializer, Serializer): ...
Register a new serializer with the importer registry.
register
python
inventree/InvenTree
src/backend/InvenTree/importer/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/registry.py
MIT
def supported_models(): """Return a map of supported models to their respective serializers.""" data = {} for serializer in get_supported_serializers(): model = serializer.Meta.model data[model.__name__.lower()] = serializer return data
Return a map of supported models to their respective serializers.
supported_models
python
inventree/InvenTree
src/backend/InvenTree/importer/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/registry.py
MIT
def supported_model_options(): """Return a list of supported model options for importing data.""" options = [] for model_name, serializer in supported_models().items(): options.append((model_name, serializer.Meta.model._meta.verbose_name)) return options
Return a list of supported model options for importing data.
supported_model_options
python
inventree/InvenTree
src/backend/InvenTree/importer/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/registry.py
MIT
def register_importer(): """Decorator function to register a serializer with the importer registry.""" def _decorator(cls): _serializer_registry.register(cls) return cls return _decorator
Decorator function to register a serializer with the importer registry.
register_importer
python
inventree/InvenTree
src/backend/InvenTree/importer/registry.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/registry.py
MIT
def __init__(self, *args, **kwargs): """Override the constructor for the DataImportSession serializer.""" super().__init__(*args, **kwargs) self.fields['model_type'].choices = importer.registry.supported_model_options()
Override the constructor for the DataImportSession serializer.
__init__
python
inventree/InvenTree
src/backend/InvenTree/importer/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/serializers.py
MIT
def create(self, validated_data): """Override create method for this serializer. Attach user information based on provided session data. """ session = super().create(validated_data) request = self.context.get('request', None) if request: session.user = requ...
Override create method for this serializer. Attach user information based on provided session data.
create
python
inventree/InvenTree
src/backend/InvenTree/importer/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/serializers.py
MIT
def validate_rows(self, rows): """Ensure that the provided rows are valid. - Row must point to the same import session - Row must contain valid data - Row must not have already been completed """ session = self.context.get('session', None) if not rows or len(row...
Ensure that the provided rows are valid. - Row must point to the same import session - Row must contain valid data - Row must not have already been completed
validate_rows
python
inventree/InvenTree
src/backend/InvenTree/importer/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/serializers.py
MIT
def import_data(session_id: int): """Load data from the provided file. Attempt to load data from the provided file, and potentially handle any errors. """ import importer.models import importer.operations import importer.status_codes try: session = importer.models.DataImportSession...
Load data from the provided file. Attempt to load data from the provided file, and potentially handle any errors.
import_data
python
inventree/InvenTree
src/backend/InvenTree/importer/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/tasks.py
MIT
def cleanup_import_sessions(): """Periodically remove old import sessions. Every 5 days, remove any importer sessions that are more than 5 days old """ CLEANUP_DAYS = 5 import importer.models if not InvenTree.tasks.check_daily_holdoff('cleanup_import_sessions', CLEANUP_DAYS): return ...
Periodically remove old import sessions. Every 5 days, remove any importer sessions that are more than 5 days old
cleanup_import_sessions
python
inventree/InvenTree
src/backend/InvenTree/importer/tasks.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/tasks.py
MIT
def test_import_session(self): """Test creation of a data import session.""" from company.models import Company n = Company.objects.count() session = DataImportSession.objects.create( data_file=self.helper_content(), model_type='company' ) session.extract_c...
Test creation of a data import session.
test_import_session
python
inventree/InvenTree
src/backend/InvenTree/importer/tests.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/tests.py
MIT
def validate_importer_model_type(value): """Validate that the given model type is supported for importing.""" from importer.registry import supported_models if value not in supported_models(): raise ValidationError(f"Unsupported model type '{value}'")
Validate that the given model type is supported for importing.
validate_importer_model_type
python
inventree/InvenTree
src/backend/InvenTree/importer/validators.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/validators.py
MIT
def validate_field_defaults(value): """Validate that the provided value is a valid dict.""" if value is None: return if type(value) is not dict: # OK if we can parse it as JSON try: value = json.loads(value) except json.JSONDecodeError: raise Validati...
Validate that the provided value is a valid dict.
validate_field_defaults
python
inventree/InvenTree
src/backend/InvenTree/importer/validators.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/importer/validators.py
MIT
def is_multifactor_logged_in(request: HttpRequest) -> bool: """Check if the user is logged in with multifactor authentication.""" authns = get_authentication_records(request) return is_mfa_enabled(request.user) and ( did_use_passwordless_login(request) or any(record.get('method') == 'mfa' f...
Check if the user is logged in with multifactor authentication.
is_multifactor_logged_in
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/AllUserRequire2FAMiddleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/AllUserRequire2FAMiddleware.py
MIT
def is_allowed_page(self, request: HttpRequest) -> bool: """Check if the current page can be accessed without mfa.""" return ( any(ref in self.app_names for ref in request.resolver_match.app_names) or request.resolver_match.url_name in self.allowed_pages or request.re...
Check if the current page can be accessed without mfa.
is_allowed_page
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/AllUserRequire2FAMiddleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/AllUserRequire2FAMiddleware.py
MIT
def get(self, request, *args, **kwargs): """Return information about the InvenTree server.""" backend = Path(__file__).parent.joinpath('licenses.txt') frontend = Path(__file__).parent.parent.joinpath( 'web/static/web/.vite/dependencies.json' ) return JsonResponse({ ...
Return information about the InvenTree server.
get
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def check_auth_header(self, request): """Check if user is authenticated via a token in the header.""" from InvenTree.middleware import get_token_from_request if token := get_token_from_request(request): # Does the provided token match a valid user? try: t...
Check if user is authenticated via a token in the header.
check_auth_header
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def get_bulk_queryset(self, request): """Return a queryset based on the selection made in the request. Selection can be made by providing either: - items: A list of primary key values - filters: A dictionary of filter values """ model = self.serializer_class.Meta.model ...
Return a queryset based on the selection made in the request. Selection can be made by providing either: - items: A list of primary key values - filters: A dictionary of filter values
get_bulk_queryset
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def patch(self, request, *args, **kwargs): """Perform a PATCH operation against this list endpoint. Note that the typical DRF list endpoint does not support PATCH, so this method is provided as a custom implementation. """ queryset = self.get_bulk_queryset(request) query...
Perform a PATCH operation against this list endpoint. Note that the typical DRF list endpoint does not support PATCH, so this method is provided as a custom implementation.
patch
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def delete(self, request, *args, **kwargs): """Perform a DELETE operation against this list endpoint. Note that the typical DRF list endpoint does not support DELETE, so this method is provided as a custom implementation. """ queryset = self.get_bulk_queryset(request) qu...
Perform a DELETE operation against this list endpoint. Note that the typical DRF list endpoint does not support DELETE, so this method is provided as a custom implementation.
delete
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def get_result_types(self): """Construct a list of search types we can return.""" import build.api import company.api import order.api import part.api import stock.api return { 'build': build.api.BuildList, 'company': company.api.CompanyLi...
Construct a list of search types we can return.
get_result_types
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def get_result_filters(self): """Provide extra filtering options for particular search groups.""" return { 'supplier': {'is_supplier': True}, 'manufacturer': {'is_manufacturer': True}, 'customer': {'is_customer': True}, }
Provide extra filtering options for particular search groups.
get_result_filters
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def post(self, request, *args, **kwargs): """Perform search query against available models.""" data = request.data results = {} # These parameters are passed through to the individual queries, with optional default values pass_through_params = { 'search': '', ...
Perform search query against available models.
post
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def as_view(cls, model, lookup_field=None, **initkwargs): """Override to ensure model specific rendering.""" if model is None: raise ValidationError( "MetadataView defined without 'model' arg" ) # pragma: no cover initkwargs['model'] = model # Se...
Override to ensure model specific rendering.
as_view
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/api.py
MIT
def ready(self): """Run system wide setup init steps. Like: - Checking if migrations should be run - Cleaning up tasks - Starting regular tasks - Updating exchange rates - Collecting notification methods - Collecting state transition methods - Add...
Run system wide setup init steps. Like: - Checking if migrations should be run - Cleaning up tasks - Starting regular tasks - Updating exchange rates - Collecting notification methods - Collecting state transition methods - Adding users set in the current...
ready
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def remove_obsolete_tasks(self): """Delete any obsolete scheduled tasks in the database.""" obsolete = [ 'InvenTree.tasks.delete_expired_sessions', 'stock.tasks.delete_old_stock_items', 'label.tasks.cleanup_old_label_outputs', 'report.tasks.cleanup_old_rep...
Delete any obsolete scheduled tasks in the database.
remove_obsolete_tasks
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def start_background_tasks(self): """Start all background tests for InvenTree.""" logger.info('Starting background tasks...') from django_q.models import Schedule # List of existing scheduled tasks (in the database) existing_tasks = {} for existing_task in Schedule.obj...
Start all background tests for InvenTree.
start_background_tasks
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def add_heartbeat(self): """Ensure there is at least one background task in the queue.""" import django_q.models try: if django_q.models.OrmQ.objects.count() == 0: InvenTree.tasks.offload_task( InvenTree.tasks.heartbeat, force_async=True ...
Ensure there is at least one background task in the queue.
add_heartbeat
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def update_exchange_rates(self): # pragma: no cover """Update exchange rates each time the server is started. Only runs *if*: a) Have not been updated recently (one day or less) b) The base exchange rate has been altered """ try: from djmoney.contrib.exchang...
Update exchange rates each time the server is started. Only runs *if*: a) Have not been updated recently (one day or less) b) The base exchange rate has been altered
update_exchange_rates
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def update_site_url(self): """Update the site URL setting. - If multi-site support is enabled, update the site URL for the current site """ if not InvenTree.ready.canAppAccessDatabase(): return if InvenTree.ready.isImportingData() or InvenTree.ready.isRunningMigrati...
Update the site URL setting. - If multi-site support is enabled, update the site URL for the current site
update_site_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def ensure_migrations_done(self=None): """Ensures there are no open migrations, stop if inconsistent state.""" global MIGRATIONS_CHECK_DONE if MIGRATIONS_CHECK_DONE: return if not InvenTree.tasks.check_for_migrations(): logger.error('INVE-W8: Database Migrations ...
Ensures there are no open migrations, stop if inconsistent state.
ensure_migrations_done
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/apps.py
MIT
def login(self, request, redirect_url=None): """Perform login action. First check that: - A valid user has been supplied """ if not self.user: # No user supplied - redirect to the login page return HttpResponseRedirect(reverse('account_login')) #...
Perform login action. First check that: - A valid user has been supplied
login
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def __init__(self, *args, **kwargs): """Check settings to influence which fields are needed.""" kwargs['email_required'] = get_global_setting('LOGIN_MAIL_REQUIRED') super().__init__(*args, **kwargs) # check for two mail fields if get_global_setting('LOGIN_SIGNUP_MAIL_TWICE'): ...
Check settings to influence which fields are needed.
__init__
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def clean(self): """Make sure the supplied emails match if enabled in settings.""" cleaned_data = super().clean() # check for two mail fields if get_global_setting('LOGIN_SIGNUP_MAIL_TWICE'): email = cleaned_data.get('email') email2 = cleaned_data.get('email2') ...
Make sure the supplied emails match if enabled in settings.
clean
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def registration_enabled(): """Determine whether user registration is enabled.""" if ( get_global_setting('LOGIN_ENABLE_REG') or InvenTree.sso.sso_registration_enabled() ): if settings.EMAIL_HOST: return True else: logger.warning( 'Regi...
Determine whether user registration is enabled.
registration_enabled
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def is_open_for_signup(self, request, *args, **kwargs): """Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE_REG`. """ if registration_enabled(): return super().is_open_for_...
Check if signup is enabled in settings. Configure the class variable `REGISTRATION_SETTING` to set which setting should be used, default: `LOGIN_ENABLE_REG`.
is_open_for_signup
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def clean_email(self, email): """Check if the mail is valid to the pattern in LOGIN_SIGNUP_MAIL_RESTRICTION (if enabled in settings).""" mail_restriction = get_global_setting('LOGIN_SIGNUP_MAIL_RESTRICTION', None) if not mail_restriction: return super().clean_email(email) sp...
Check if the mail is valid to the pattern in LOGIN_SIGNUP_MAIL_RESTRICTION (if enabled in settings).
clean_email
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def save_user(self, request, user, form, commit=True): """Check if a default group is set in settings.""" # Create the user user = super().save_user(request, user, form) # Check if a default group is set in settings start_group = get_global_setting('SIGNUP_GROUP') if ( ...
Check if a default group is set in settings.
save_user
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def send_mail(self, template_prefix, email, context): """Only send mail if backend configured.""" if settings.EMAIL_HOST: try: result = super().send_mail(template_prefix, email, context) except Exception: # An exception occurred while attempting to...
Only send mail if backend configured.
send_mail
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def is_auto_signup_allowed(self, request, sociallogin): """Check if auto signup is enabled in settings.""" if get_global_setting('LOGIN_SIGNUP_SSO_AUTO', True): return super().is_auto_signup_allowed(request, sociallogin) return False
Check if auto signup is enabled in settings.
is_auto_signup_allowed
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def get_frontend_url(self, urlname, **kwargs): """Get the frontend URL for the given URL name respecting the request.""" HEADLESS_FRONTEND_URLS = { 'account_confirm_email': 'verify-email/{key}', 'account_reset_password': 'reset-password', 'account_reset_password_from_...
Get the frontend URL for the given URL name respecting the request.
get_frontend_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/auth_overrides.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/auth_overrides.py
MIT
def get_value(self) -> bool: """Get the current state of the maintenance mode. Returns: bool: True if maintenance mode is active, False otherwise. """ try: value = get_global_setting(self.SETTING_KEY) except Exception: # Database is inaccessib...
Get the current state of the maintenance mode. Returns: bool: True if maintenance mode is active, False otherwise.
get_value
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/backends.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/backends.py
MIT
def set_value(self, value: bool, retries: int = 5, minutes: int = 5): """Set the state of the maintenance mode. Instead of simply writing "true" or "false" to the setting, we write a timestamp to the setting, which is used to determine when maintenance mode will elapse. This ens...
Set the state of the maintenance mode. Instead of simply writing "true" or "false" to the setting, we write a timestamp to the setting, which is used to determine when maintenance mode will elapse. This ensures that we will always *exit* maintenance mode after a certain time period. ...
set_value
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/backends.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/backends.py
MIT
def cache_setting(name, default=None, **kwargs): """Return the value of a particular cache setting. Arguments: name: The name of the cache setting default: The default value to return if the setting is not found kwargs: Additional arguments to pass to the cache setting request """ ...
Return the value of a particular cache setting. Arguments: name: The name of the cache setting default: The default value to return if the setting is not found kwargs: Additional arguments to pass to the cache setting request
cache_setting
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/cache.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/cache.py
MIT
def is_global_cache_enabled() -> bool: """Check if the global cache is enabled. - Test if the user has enabled and configured global cache - Test if it is appropriate to enable global cache based on the current operation. """ host = cache_host() # Test if cache is enabled # If the cache ho...
Check if the global cache is enabled. - Test if the user has enabled and configured global cache - Test if it is appropriate to enable global cache based on the current operation.
is_global_cache_enabled
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/cache.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/cache.py
MIT
def get_cache_config(global_cache: bool) -> dict: """Return the cache configuration options. Args: global_cache: True if the global cache is enabled. Returns: A dictionary containing the cache configuration options. """ if global_cache: return { 'BACKEND': 'django...
Return the cache configuration options. Args: global_cache: True if the global cache is enabled. Returns: A dictionary containing the cache configuration options.
get_cache_config
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/cache.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/cache.py
MIT