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 delete_session_cache() -> None: """Remove the session cache once the request is complete.""" if hasattr(thread_data, 'request'): del thread_data.request if hasattr(thread_data, 'request_cache'): del thread_data.request_cache
Remove the session cache once the request is complete.
delete_session_cache
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_session_cache(key: str) -> any: """Return a cached value from the session cache.""" # Only return a cached value if the request object is available too if not hasattr(thread_data, 'request'): return None request_cache = getattr(thread_data, 'request_cache', None) if request_cache is...
Return a cached value from the session cache.
get_session_cache
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/cache.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/cache.py
MIT
def set_session_cache(key: str, value: any) -> None: """Set a cached value in the session cache.""" # Only set a cached value if the request object is available too if not hasattr(thread_data, 'request'): return request_cache = getattr(thread_data, 'request_cache', None) if request_cache i...
Set a cached value in the session cache.
set_session_cache
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/cache.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/cache.py
MIT
def to_dict(value): """Take a configuration setting and make sure it is a dict. For example, we might have a configuration setting taken from the .config file, which is already an object/dict. However, the same setting may be specified via an environment variable, using a valid JSON string! ""...
Take a configuration setting and make sure it is a dict. For example, we might have a configuration setting taken from the .config file, which is already an object/dict. However, the same setting may be specified via an environment variable, using a valid JSON string!
to_dict
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def ensure_dir(path: Path, storage=None) -> None: """Ensure that a directory exists. If it does not exist, create it. """ from django.core.files.base import ContentFile from django.core.files.storage import Storage if storage and isinstance(storage, Storage): if not storage.exists(str(...
Ensure that a directory exists. If it does not exist, create it.
ensure_dir
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_config_file(create=True) -> Path: """Returns the path of the InvenTree configuration file. Note: It will be created it if does not already exist! """ base_dir = get_base_dir() cfg_filename = os.getenv('INVENTREE_CONFIG_FILE') if cfg_filename: cfg_filename = Path(cfg_filename.s...
Returns the path of the InvenTree configuration file. Note: It will be created it if does not already exist!
get_config_file
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def load_config_data(set_cache: bool = False) -> map: """Load configuration data from the config file. Arguments: set_cache(bool): If True, the configuration data will be cached for future use after load. """ global CONFIG_DATA # use cache if populated # skip cache if cache should be s...
Load configuration data from the config file. Arguments: set_cache(bool): If True, the configuration data will be cached for future use after load.
load_config_data
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def do_typecast(value, type, var_name=None): """Attempt to typecast a value. Arguments: value: Value to typecast type: Function to use for typecasting the value e.g. int, float, str, list, dict var_name: Name that should be logged e.g. 'INVENTREE_STATIC_ROOT'. Set if logging is required...
Attempt to typecast a value. Arguments: value: Value to typecast type: Function to use for typecasting the value e.g. int, float, str, list, dict var_name: Name that should be logged e.g. 'INVENTREE_STATIC_ROOT'. Set if logging is required. Returns: Typecast value or original v...
do_typecast
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_setting(env_var=None, config_key=None, default_value=None, typecast=None): """Helper function for retrieving a configuration setting value. - First preference is to look for the environment variable - Second preference is to look for the value of the settings file - Third preference is the defa...
Helper function for retrieving a configuration setting value. - First preference is to look for the environment variable - Second preference is to look for the value of the settings file - Third preference is the default value Arguments: env_var: Name of the environment variable e.g. 'INVENTRE...
get_setting
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def set_metadata(source: str): """Set lookup metadata for the setting.""" key = env_var or config_key CONFIG_LOOKUPS[key] = { 'env_var': env_var, 'config_key': config_key, 'source': source, 'accessed': datetime.datetime.now(), }
Set lookup metadata for the setting.
set_metadata
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_media_dir(create=True, error=True): """Return the absolute path for the 'media' directory (where uploaded files are stored).""" md = get_setting('INVENTREE_MEDIA_ROOT', 'media_root') if not md: if error: raise FileNotFoundError('INVENTREE_MEDIA_ROOT not specified') else:...
Return the absolute path for the 'media' directory (where uploaded files are stored).
get_media_dir
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_static_dir(create=True, error=True): """Return the absolute path for the 'static' directory (where static files are stored).""" sd = get_setting('INVENTREE_STATIC_ROOT', 'static_root') if not sd: if error: raise FileNotFoundError('INVENTREE_STATIC_ROOT not specified') el...
Return the absolute path for the 'static' directory (where static files are stored).
get_static_dir
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_backup_dir(create=True, error=True): """Return the absolute path for the backup directory.""" bd = get_setting('INVENTREE_BACKUP_DIR', 'backup_dir') if not bd: if error: raise FileNotFoundError('INVENTREE_BACKUP_DIR not specified') else: return None bd =...
Return the absolute path for the backup directory.
get_backup_dir
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_plugin_file(): """Returns the path of the InvenTree plugins specification file. Note: It will be created if it does not already exist! """ # Check if the plugin.txt file (specifying required plugins) is specified plugin_file = get_setting('INVENTREE_PLUGIN_FILE', 'plugin_file') if not ...
Returns the path of the InvenTree plugins specification file. Note: It will be created if it does not already exist!
get_plugin_file
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_secret_key(): """Return the secret key value which will be used by django. Following options are tested, in descending order of preference: A) Check for environment variable INVENTREE_SECRET_KEY => Use raw key data B) Check for environment variable INVENTREE_SECRET_KEY_FILE => Load key data fr...
Return the secret key value which will be used by django. Following options are tested, in descending order of preference: A) Check for environment variable INVENTREE_SECRET_KEY => Use raw key data B) Check for environment variable INVENTREE_SECRET_KEY_FILE => Load key data from file C) Look for defau...
get_secret_key
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_oidc_private_key(): """Return the private key for OIDC authentication. Following options are tested, in descending order of preference: A) Check for environment variable INVENTREE_OIDC_PRIVATE_KEY or config yalue => Use raw key data B) Check for environment variable INVENTREE_OIDC_PRIVATE_KEY_F...
Return the private key for OIDC authentication. Following options are tested, in descending order of preference: A) Check for environment variable INVENTREE_OIDC_PRIVATE_KEY or config yalue => Use raw key data B) Check for environment variable INVENTREE_OIDC_PRIVATE_KEY_FILE or config value => Load key da...
get_oidc_private_key
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_custom_file( env_ref: str, conf_ref: str, log_ref: str, lookup_media: bool = False ): """Returns the checked path to a custom file. Set lookup_media to True to also search in the media folder. """ from django.contrib.staticfiles.storage import StaticFilesStorage from django.core.files.s...
Returns the checked path to a custom file. Set lookup_media to True to also search in the media folder.
get_custom_file
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_frontend_settings(debug=True): """Return a dictionary of settings for the frontend interface.""" # New settings frontend_settings = get_setting( 'INVENTREE_FRONTEND_SETTINGS', 'frontend_settings', {}, typecast=dict ) # Set the base URL for the user interface # This is the UI pat...
Return a dictionary of settings for the frontend interface.
get_frontend_settings
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/config.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/config.py
MIT
def get_unit_registry(): """Return a custom instance of the Pint UnitRegistry.""" global _unit_registry # Cache the unit registry for speedier access if _unit_registry is None: return reload_unit_registry() return _unit_registry
Return a custom instance of the Pint UnitRegistry.
get_unit_registry
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def reload_unit_registry(): """Reload the unit registry from the database. This function is called at startup, and whenever the database is updated. """ import time t_start = time.time() global _unit_registry _unit_registry = None reg = pint.UnitRegistry(autoconvert_offset_to_baseun...
Reload the unit registry from the database. This function is called at startup, and whenever the database is updated.
reload_unit_registry
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def from_engineering_notation(value): """Convert a provided value to 'natural' representation from 'engineering' notation. Ref: https://en.wikipedia.org/wiki/Engineering_notation In "engineering notation", the unit (or SI prefix) is often combined with the value, and replaces the decimal point. E...
Convert a provided value to 'natural' representation from 'engineering' notation. Ref: https://en.wikipedia.org/wiki/Engineering_notation In "engineering notation", the unit (or SI prefix) is often combined with the value, and replaces the decimal point. Examples: - 1K2 -> 1.2K - 3n05 -> 3.05...
from_engineering_notation
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def convert_value(value, unit): """Attempt to convert a value to a specified unit. Arguments: value: The value to convert unit: The target unit to convert to Returns: The converted value (ideally a pint.Quantity value) Raises: Exception if the value cannot be converted...
Attempt to convert a value to a specified unit. Arguments: value: The value to convert unit: The target unit to convert to Returns: The converted value (ideally a pint.Quantity value) Raises: Exception if the value cannot be converted to the specified unit
convert_value
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def convert_physical_value(value: str, unit: Optional[str] = None, strip_units=True): """Validate that the provided value is a valid physical quantity. Arguments: value: Value to validate (str) unit: Optional unit to convert to, and validate against strip_units: If True, strip units fro...
Validate that the provided value is a valid physical quantity. Arguments: value: Value to validate (str) unit: Optional unit to convert to, and validate against strip_units: If True, strip units from the returned value, and return only the dimension Raises: ValidationError: If ...
convert_physical_value
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def is_dimensionless(value): """Determine if the provided value is 'dimensionless'. A dimensionless value might look like: 0.1 1/2 dozen three thousand 1.2 dozen (etc) """ ureg = get_unit_registry() # Ensure the provided value is in the right format value = ureg.Quantity(v...
Determine if the provided value is 'dimensionless'. A dimensionless value might look like: 0.1 1/2 dozen three thousand 1.2 dozen (etc)
is_dimensionless
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/conversion.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/conversion.py
MIT
def log_error( path, error_name=None, error_info=None, error_data=None, plugin: Optional[str] = None, ): """Log an error to the database. - Uses python exception handling to extract error details Arguments: path: The 'path' (most likely a URL) associated with this error (option...
Log an error to the database. - Uses python exception handling to extract error details Arguments: path: The 'path' (most likely a URL) associated with this error (optional) kwargs: error_name: The name of the error (optional, overrides 'kind') error_info: The error information (o...
log_error
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/exceptions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/exceptions.py
MIT
def exception_handler(exc, context): """Custom exception handler for DRF framework. Ref: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling Catches any errors not natively handled by DRF, and re-throws as an error DRF can handle. If sentry error reporting is enabled,...
Custom exception handler for DRF framework. Ref: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling Catches any errors not natively handled by DRF, and re-throws as an error DRF can handle. If sentry error reporting is enabled, we will also provide the original exception...
exception_handler
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/exceptions.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/exceptions.py
MIT
def get_rates(self, **kwargs) -> dict: """Set the requested currency codes and get rates.""" from plugin import PluginMixinEnum, registry base_currency = kwargs.get('base_currency', currency_code_default()) symbols = kwargs.get('symbols', currency_codes()) # Find the selected e...
Set the requested currency codes and get rates.
get_rates
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/exchange.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/exchange.py
MIT
def update_rates(self, base_currency=None, **kwargs): """Call to update all exchange rates.""" backend, _ = ExchangeBackend.objects.update_or_create( name=self.name, defaults={'base_currency': base_currency} ) if base_currency is None: base_currency = currency_co...
Call to update all exchange rates.
update_rates
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/exchange.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/exchange.py
MIT
def run_validation(self, data=empty): """Override default validation behavior for this field type.""" strict_urls = get_global_setting('INVENTREE_STRICT_URLS', cache=False) if not strict_urls and data is not empty and data is not None: data = str(data).strip() if data an...
Override default validation behavior for this field type.
run_validation
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/fields.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/fields.py
MIT
def money_kwargs(**kwargs): """Returns the database settings for MoneyFields.""" from common.currency import currency_code_default, currency_code_mappings # Default values (if not specified) if 'max_digits' not in kwargs: kwargs['max_digits'] = 19 if 'decimal_places' not in kwargs: ...
Returns the database settings for MoneyFields.
money_kwargs
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/fields.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/fields.py
MIT
def round_decimal(value, places, normalize=False): """Round value to the specified number of places.""" if type(value) in [Decimal, float]: try: value = round(value, places) except Exception: raise ValidationError(_('Invalid decimal value') + f' ({value})') if no...
Round value to the specified number of places.
round_decimal
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/fields.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/fields.py
MIT
def __init__(self, **kwargs): """Configure default initial values for this field.""" kwargs['max_length'] = self.NOTES_MAX_LENGTH kwargs['verbose_name'] = _('Notes') kwargs['blank'] = True kwargs['null'] = True super().__init__(**kwargs)
Configure default initial values for this field.
__init__
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/fields.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/fields.py
MIT
def filter(self, qs, value): """Override the filter method to handle timezones correctly.""" if settings.USE_TZ and value is not None: tz = timezone.get_current_timezone() value = datetime(value.year, value.month, value.day) value = make_aware(value, tz, True) ...
Override the filter method to handle timezones correctly.
filter
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/filters.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/filters.py
MIT
def get_search_fields(self, view, request): """Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' the search (in decreasing order of priority) - search_notes: If True, 'notes' is added to the search_fields if it...
Return a set of search fields for the request, adjusted based on request params. The following query params are available to 'augment' the search (in decreasing order of priority) - search_notes: If True, 'notes' is added to the search_fields if it isn't already present - search_regex: If True,...
get_search_fields
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/filters.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/filters.py
MIT
def get_search_terms(self, request): """Return the search terms for this search request. Depending on the request parameters, we may "augment" these somewhat """ whole = InvenTree.helpers.str2bool( request.query_params.get('search_whole', False) ) terms = []...
Return the search terms for this search request. Depending on the request parameters, we may "augment" these somewhat
get_search_terms
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/filters.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/filters.py
MIT
def parse_format_string(fmt_string: str) -> dict: """Extract formatting information from the provided format string. Returns a dict object which contains structured information about the format groups """ groups = string.Formatter().parse(fmt_string) info = {} seen_groups = set() for gro...
Extract formatting information from the provided format string. Returns a dict object which contains structured information about the format groups
parse_format_string
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/format.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/format.py
MIT
def construct_format_regex(fmt_string: str) -> str: r"""Construct a regular expression based on a provided format string. This function turns a python format string into a regular expression, which can be used for two purposes: - Ensure that a particular string matches the specified format - Extra...
Construct a regular expression based on a provided format string. This function turns a python format string into a regular expression, which can be used for two purposes: - Ensure that a particular string matches the specified format - Extract named variables from a matching string This function...
construct_format_regex
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/format.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/format.py
MIT
def validate_string(value: str, fmt_string: str) -> str: """Validate that the provided string matches the specified format. Args: value: The string to be tested e.g. 'SO-1234-ABC', fmt_string: The required format e.g. 'SO-{ref}-???', Returns: bool: True if the value matches the req...
Validate that the provided string matches the specified format. Args: value: The string to be tested e.g. 'SO-1234-ABC', fmt_string: The required format e.g. 'SO-{ref}-???', Returns: bool: True if the value matches the required format, else False Raises: ValueError: The pr...
validate_string
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/format.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/format.py
MIT
def extract_named_group(name: str, value: str, fmt_string: str) -> str: """Extract a named value from the provided string, given the provided format string. Args: name: Name of group to extract e.g. 'ref' value: Raw string e.g. 'PO-ABC-1234' fmt_string: Format pattern e.g. 'PO-???-{ref}...
Extract a named value from the provided string, given the provided format string. Args: name: Name of group to extract e.g. 'ref' value: Raw string e.g. 'PO-ABC-1234' fmt_string: Format pattern e.g. 'PO-???-{ref} Returns: str: String value of the named group Raises: ...
extract_named_group
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/format.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/format.py
MIT
def format_money( money: Money, decimal_places: Optional[int] = None, fmt: Optional[str] = None, include_symbol: bool = True, ) -> str: """Format money object according to the currently set local. Args: money (Money): The money object to format decimal_places (int): Number of de...
Format money object according to the currently set local. Args: money (Money): The money object to format decimal_places (int): Number of decimal places to use fmt (str): Format pattern according LDML / the babel format pattern syntax (https://babel.pocoo.org/en/latest/numbers.html) ...
format_money
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/format.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/format.py
MIT
def extract_int( reference, clip=INT_CLIP_MAX, try_hex=False, allow_negative=False ) -> int: """Extract an integer out of provided string. Arguments: reference: Input string to extract integer from clip: Maximum value to return (default = 0x7FFFFFFF) try_hex: Attempt to parse as hex...
Extract an integer out of provided string. Arguments: reference: Input string to extract integer from clip: Maximum value to return (default = 0x7FFFFFFF) try_hex: Attempt to parse as hex if integer conversion fails (default = False) allow_negative: Allow negative values (default = ...
extract_int
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def do_clip(value: int, clip: int, allow_negative: bool) -> int: """Perform clipping on the provided value. Arguments: value: Value to clip clip: Maximum value to clip to allow_negative: Allow negative values (default = False) """ if clip is None: ...
Perform clipping on the provided value. Arguments: value: Value to clip clip: Maximum value to clip to allow_negative: Allow negative values (default = False)
do_clip
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def generateTestKey(test_name: str) -> str: """Generate a test 'key' for a given test name. This must not have illegal chars as it will be used for dict lookup in a template. Tests must be named such that they will have unique keys. """ if test_name is None: test_name = '' key = test_name....
Generate a test 'key' for a given test name. This must not have illegal chars as it will be used for dict lookup in a template. Tests must be named such that they will have unique keys.
generateTestKey
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def valid_char(char: str): """Determine if a particular character is valid for use in a test key.""" if not char.isprintable(): return False if char.isidentifier(): return True return bool(char.isalnum())
Determine if a particular character is valid for use in a test key.
valid_char
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def constructPathString(path, max_chars=250): """Construct a 'path string' for the given path. Arguments: path: A list of strings e.g. ['path', 'to', 'location'] max_chars: Maximum number of characters """ pathstring = '/'.join(path) # Replace middle elements to limit the pathstrin...
Construct a 'path string' for the given path. Arguments: path: A list of strings e.g. ['path', 'to', 'location'] max_chars: Maximum number of characters
constructPathString
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def TestIfImage(img): """Test if an image file is indeed an image.""" try: Image.open(img).verify() return True except Exception: return False
Test if an image file is indeed an image.
TestIfImage
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def getLogoImage(as_file=False, custom=True): """Return the InvenTree logo image, or a custom logo if available.""" """Return the path to the logo-file.""" if custom and settings.CUSTOM_LOGO: static_storage = StaticFilesStorage() if static_storage.exists(settings.CUSTOM_LOGO): s...
Return the InvenTree logo image, or a custom logo if available.
getLogoImage
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def getSplashScreen(custom=True): """Return the InvenTree splash screen, or a custom splash if available.""" static_storage = StaticFilesStorage() if custom and settings.CUSTOM_SPLASH: if static_storage.exists(settings.CUSTOM_SPLASH): return static_storage.url(settings.CUSTOM_SPLASH) ...
Return the InvenTree splash screen, or a custom splash if available.
getSplashScreen
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def TestIfImageURL(url): """Test if an image URL (or filename) looks like a valid image format. Simply tests the extension against a set of allowed values """ return os.path.splitext(os.path.basename(url))[-1].lower() in [ '.jpg', '.jpeg', '.j2k', '.png', '.bmp',...
Test if an image URL (or filename) looks like a valid image format. Simply tests the extension against a set of allowed values
TestIfImageURL
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def str2bool(text, test=True): """Test if a string 'looks' like a boolean value. Args: text: Input text test (default = True): Set which boolean value to look for Returns: True if the text looks like the selected boolean value """ if test: return str(text).lower() i...
Test if a string 'looks' like a boolean value. Args: text: Input text test (default = True): Set which boolean value to look for Returns: True if the text looks like the selected boolean value
str2bool
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def isNull(text): """Test if a string 'looks' like a null value. This is useful for querying the API against a null key. Args: text: Input text Returns: True if the text looks like a null value """ return str(text).strip().lower() in [ 'top', 'null', 'none',...
Test if a string 'looks' like a null value. This is useful for querying the API against a null key. Args: text: Input text Returns: True if the text looks like a null value
isNull
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def normalize(d): """Normalize a decimal number, and remove exponential formatting.""" if type(d) is not Decimal: d = Decimal(d) d = d.normalize() # Ref: https://docs.python.org/3/library/decimal.html return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Normalize a decimal number, and remove exponential formatting.
normalize
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def increment(value): """Attempt to increment an integer (or a string that looks like an integer). e.g. 001 -> 002 2 -> 3 AB01 -> AB02 QQQ -> QQQ """ # Ignore empty strings if value in ['', None]: # Provide a default value if provided with a null input return '1' ...
Attempt to increment an integer (or a string that looks like an integer). e.g. 001 -> 002 2 -> 3 AB01 -> AB02 QQQ -> QQQ
increment
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def decimal2string(d): """Format a Decimal number as a string, stripping out any trailing zeroes or decimal points. Essentially make it look like a whole number if it is one. Args: d: A python Decimal object Returns: A string representation of the input number """ if type(d) is Dec...
Format a Decimal number as a string, stripping out any trailing zeroes or decimal points. Essentially make it look like a whole number if it is one. Args: d: A python Decimal object Returns: A string representation of the input number
decimal2string
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def decimal2money(d, currency=None): """Format a Decimal number as Money. Args: d: A python Decimal object currency: Currency of the input amount, defaults to default currency in settings Returns: A Money object from the input(s) """ if not currency: currency = curr...
Format a Decimal number as Money. Args: d: A python Decimal object currency: Currency of the input amount, defaults to default currency in settings Returns: A Money object from the input(s)
decimal2money
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def WrapWithQuotes(text, quote='"'): """Wrap the supplied text with quotes. Args: text: Input text to wrap quote: Quote character to use for wrapping (default = "") Returns: Supplied text wrapped in quote char """ if not text.startswith(quote): text = quote + text ...
Wrap the supplied text with quotes. Args: text: Input text to wrap quote: Quote character to use for wrapping (default = "") Returns: Supplied text wrapped in quote char
WrapWithQuotes
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def DownloadFile( data, filename, content_type='application/text', inline=False ) -> StreamingHttpResponse: """Create a dynamic file for the user to download. Args: data: Raw file data (string or bytes) filename: Filename for the file download content_type: Content type for the down...
Create a dynamic file for the user to download. Args: data: Raw file data (string or bytes) filename: Filename for the file download content_type: Content type for the download inline: Download "inline" or as attachment? (Default = attachment) Return: A StreamingHttpRes...
DownloadFile
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def increment_serial_number(serial, part=None): """Given a serial number, (attempt to) generate the *next* serial number. Note: This method is exposed to custom plugins. Arguments: serial: The serial number which should be incremented part: Optional part object to provide additional contex...
Given a serial number, (attempt to) generate the *next* serial number. Note: This method is exposed to custom plugins. Arguments: serial: The serial number which should be incremented part: Optional part object to provide additional context for incrementing the serial number Returns: ...
increment_serial_number
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def add_serial(serial): """Helper function to check for duplicated values.""" serial = serial.strip() # Ignore blank / empty serials if len(serial) == 0: return if serial in serials: add_error(_('Duplicate serial') + f': {serial}') else: ...
Helper function to check for duplicated values.
add_serial
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def validateFilterString(value, model=None): """Validate that a provided filter string looks like a list of comma-separated key=value pairs. These should nominally match to a valid database filter based on the model being filtered. e.g. "category=6, IPN=12" e.g. "part__name=widget" The ReportTemp...
Validate that a provided filter string looks like a list of comma-separated key=value pairs. These should nominally match to a valid database filter based on the model being filtered. e.g. "category=6, IPN=12" e.g. "part__name=widget" The ReportTemplate class uses the filter string to work out which ...
validateFilterString
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def strip_html_tags(value: str, raise_error=True, field_name=None): """Strip HTML tags from an input string using the bleach library. If raise_error is True, a ValidationError will be thrown if HTML tags are detected """ value = str(value).strip() cleaned = clean(value, strip=True, tags=[], attrib...
Strip HTML tags from an input string using the bleach library. If raise_error is True, a ValidationError will be thrown if HTML tags are detected
strip_html_tags
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def remove_non_printable_characters(value: str, remove_newline=True) -> str: """Remove non-printable / control characters from the provided string.""" cleaned = value # Remove ASCII control characters # Note that we do not sub out 0x0A (\n) here, it is done separately below regex = re.compile(r'[\u...
Remove non-printable / control characters from the provided string.
remove_non_printable_characters
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def clean_markdown(value: str) -> str: """Clean a markdown string. This function will remove javascript and other potentially harmful content from the markdown string. """ import markdown try: markdownify_settings = settings.MARKDOWNIFY['default'] except (AttributeError, KeyError): ...
Clean a markdown string. This function will remove javascript and other potentially harmful content from the markdown string.
clean_markdown
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def hash_barcode(barcode_data: str) -> str: """Calculate a 'unique' hash for a barcode string. This hash is used for comparison / lookup. We first remove any non-printable characters from the barcode data, as some browsers have issues scanning characters in. """ barcode_data = str(barcode_data...
Calculate a 'unique' hash for a barcode string. This hash is used for comparison / lookup. We first remove any non-printable characters from the barcode data, as some browsers have issues scanning characters in.
hash_barcode
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def current_time(local=True): """Return the current date and time as a datetime object. - If timezone support is active, returns a timezone aware time - If timezone support is not active, returns a timezone naive time Arguments: local: Return the time in the local timezone, otherwise UTC (defa...
Return the current date and time as a datetime object. - If timezone support is active, returns a timezone aware time - If timezone support is not active, returns a timezone naive time Arguments: local: Return the time in the local timezone, otherwise UTC (default = True)
current_time
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def to_local_time(time, target_tz: Optional[str] = None): """Convert the provided time object to the local timezone. Arguments: time: The time / date to convert target_tz: The desired timezone (string) - defaults to server time Returns: A timezone aware datetime object, with the de...
Convert the provided time object to the local timezone. Arguments: time: The time / date to convert target_tz: The desired timezone (string) - defaults to server time Returns: A timezone aware datetime object, with the desired timezone Raises: TypeError: If the provided ti...
to_local_time
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def get_objectreference( obj, type_ref: str = 'content_type', object_ref: str = 'object_id' ): """Lookup method for the GenericForeignKey fields. Attributes: - obj: object that will be resolved - type_ref: field name for the contenttype field in the model - object_ref: field name for the object...
Lookup method for the GenericForeignKey fields. Attributes: - obj: object that will be resolved - type_ref: field name for the contenttype field in the model - object_ref: field name for the object id in the model Example implementation in the serializer: ``` target = serializers.Serialize...
get_objectreference
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def inheritors( cls: type[Inheritors_T], subclasses: bool = True ) -> set[type[Inheritors_T]]: """Return all classes that are subclasses from the supplied cls. Args: cls: The class to search for subclasses subclasses: Include subclasses of subclasses (default = True) """ subcls = se...
Return all classes that are subclasses from the supplied cls. Args: cls: The class to search for subclasses subclasses: Include subclasses of subclasses (default = True)
inheritors
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def pui_url(subpath: str) -> str: """Return the URL for a web subpath.""" if not subpath.startswith('/'): subpath = '/' + subpath return f'/{settings.FRONTEND_URL_BASE}{subpath}'
Return the URL for a web subpath.
pui_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers.py
MIT
def is_email_configured(): """Check if email backend is configured. NOTE: This does not check if the configuration is valid! """ configured = True testing = settings.TESTING if InvenTree.ready.isInTestMode(): return False if InvenTree.ready.isImportingData(): return False ...
Check if email backend is configured. NOTE: This does not check if the configuration is valid!
is_email_configured
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_email.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_email.py
MIT
def send_email(subject, body, recipients, from_email=None, html_message=None): """Send an email with the specified subject and body, to the specified recipients list.""" if isinstance(recipients, str): recipients = [recipients] import InvenTree.ready if InvenTree.ready.isImportingData(): ...
Send an email with the specified subject and body, to the specified recipients list.
send_email
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_email.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_email.py
MIT
def get_email_for_user(user) -> str: """Find an email address for the specified user.""" # First check if the user has an associated email address if user.email: return user.email # Otherwise, find first matching email # Priority is given to primary or verified email addresses if ( ...
Find an email address for the specified user.
get_email_for_user
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_email.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_email.py
MIT
def validate(cls): """Validate the class against the required attributes/overrides.""" def attribute_missing(key): """Check if attribute is missing.""" return not hasattr(cls, key) or getattr(cls, key) == '' def override_missing(base_implementation): """Chec...
Validate the class against the required attributes/overrides.
validate
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_mixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_mixin.py
MIT
def get_provider_plugin(cls): """Plugin that contains the Class definition, otherwise None.""" for plg in plg_registry.plugins.values(): if plg.package_path == cls.__module__: return plg
Plugin that contains the Class definition, otherwise None.
get_provider_plugin
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_mixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_mixin.py
MIT
def get_is_builtin(cls): """Is this Class build in the InvenTree source code?""" try: Path(cls.get_provider_file()).relative_to(settings.BASE_DIR) return True except ValueError: # Path(...).relative_to throws an ValueError if its not relative to the InvenTree ...
Is this Class build in the InvenTree source code?
get_is_builtin
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_mixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_mixin.py
MIT
def get_shared_class_instance_state_mixin(get_state_key: Callable[[type], str]): """Get a mixin class that provides shared state for classes across the main application and worker. Arguments: get_state_key: A function that returns the key for the shared state when given a class instance. """ c...
Get a mixin class that provides shared state for classes across the main application and worker. Arguments: get_state_key: A function that returns the key for the shared state when given a class instance.
get_shared_class_instance_state_mixin
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_mixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_mixin.py
MIT
def get_base_url(request=None) -> str: """Return the base URL for the InvenTree server. The base URL is determined in the following order of decreasing priority: 1. If a request object is provided, use the request URL 2. Multi-site is enabled, and the current site has a valid URL 3. If settings.SI...
Return the base URL for the InvenTree server. The base URL is determined in the following order of decreasing priority: 1. If a request object is provided, use the request URL 2. Multi-site is enabled, and the current site has a valid URL 3. If settings.SITE_URL is set (e.g. in the Django settings), u...
get_base_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def construct_absolute_url(*arg, base_url=None, request=None): """Construct (or attempt to construct) an absolute URL from a relative URL. Args: *arg: The relative URL to construct base_url: The base URL to use for the construction (if not provided, will attempt to determine from settings) ...
Construct (or attempt to construct) an absolute URL from a relative URL. Args: *arg: The relative URL to construct base_url: The base URL to use for the construction (if not provided, will attempt to determine from settings) request: The request object to use for the construction (optional)...
construct_absolute_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def download_image_from_url(remote_url, timeout=2.5): """Download an image file from a remote URL. This is a potentially dangerous operation, so we must perform some checks: - The remote URL is available - The Content-Length is provided, and is not too large - The file is a valid image file Ar...
Download an image file from a remote URL. This is a potentially dangerous operation, so we must perform some checks: - The remote URL is available - The Content-Length is provided, and is not too large - The file is a valid image file Arguments: remote_url: The remote URL to retrieve image...
download_image_from_url
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def render_currency( money: Money, decimal_places: Optional[int] = None, currency: Optional[str] = None, min_decimal_places: Optional[int] = None, max_decimal_places: Optional[int] = None, include_symbol: bool = True, ): """Render a currency / Money object to a formatted string (e.g. for rep...
Render a currency / Money object to a formatted string (e.g. for reports). Arguments: money: The Money instance to be rendered decimal_places: The number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES setting. currency: Optionally convert to the specified cu...
render_currency
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def getModelsWithMixin(mixin_class) -> list: """Return a list of database models that inherit from the given mixin class. Args: mixin_class: The mixin class to search for Returns: List of models that inherit from the given mixin class """ from django.contrib.contenttypes.models impo...
Return a list of database models that inherit from the given mixin class. Args: mixin_class: The mixin class to search for Returns: List of models that inherit from the given mixin class
getModelsWithMixin
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def notify_responsible( instance, sender, content: NotificationBody = InvenTreeNotificationBodies.NewOrder, exclude=None, extra_users: Optional[list] = None, ): """Notify all responsible parties of a change in an instance. Parses the supplied content with the provided instance and sender an...
Notify all responsible parties of a change in an instance. Parses the supplied content with the provided instance and sender and sends a notification to all responsible users, excluding the optional excluded list. Args: instance: The newly created instance sender: Sender model reference ...
notify_responsible
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def notify_users( users, instance, sender, content: NotificationBody = InvenTreeNotificationBodies.NewOrder, exclude=None, ): """Notify all passed users or groups. Parses the supplied content with the provided instance and sender and sends a notification to all users, excluding the opti...
Notify all passed users or groups. Parses the supplied content with the provided instance and sender and sends a notification to all users, excluding the optional excluded list. Args: users: List of users or groups to notify instance: The newly created instance sender: Sender model...
notify_users
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/helpers_model.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/helpers_model.py
MIT
def send_simple_login_email(user, link): """Send an email with the login link to this user.""" site_name = InvenTree.version.inventreeInstanceName() context = {'username': user.username, 'site_name': site_name, 'link': link} email_plaintext_message = render_to_string( 'InvenTree/user_simple_log...
Send an email with the login link to this user.
send_simple_login_email
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/magic_login.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/magic_login.py
MIT
def post(self, request, *args, **kwargs): """Get the token for the current user or fail.""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) self.email_submitted(email=serializer.data['email']) return Response({'status': 'ok'})
Get the token for the current user or fail.
post
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/magic_login.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/magic_login.py
MIT
def get_user(self, email): """Find the user with this email address.""" try: return User.objects.get(email=email) except User.DoesNotExist: return None
Find the user with this email address.
get_user
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/magic_login.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/magic_login.py
MIT
def create_link(self, user): """Create a login link for this user.""" link = reverse('sesame-login') link = self.request.build_absolute_uri(link) link += sesame.utils.get_query_string(user) return link
Create a login link for this user.
create_link
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/magic_login.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/magic_login.py
MIT
def determine_actions(self, request, view): """Determine the 'actions' available to the user for the given view. Note that this differs from the standard DRF implementation, in that we also allow annotation for the 'GET' method. This allows the client to determine what fields are avail...
Determine the 'actions' available to the user for the given view. Note that this differs from the standard DRF implementation, in that we also allow annotation for the 'GET' method. This allows the client to determine what fields are available, even if they are only for a read (GET) op...
determine_actions
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/metadata.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/metadata.py
MIT
def determine_metadata(self, request, view): """Overwrite the metadata to adapt to the request user.""" self.request = request self.view = view metadata = super().determine_metadata(request, view) """ Custom context information to pass through to the OPTIONS endpoint, ...
Overwrite the metadata to adapt to the request user.
determine_metadata
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/metadata.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/metadata.py
MIT
def override_value(self, field_name: str, field_key: str, field_value, model_value): """Override a value on the serializer with a matching value for the model. Often, the serializer field will point to an underlying model field, which contains extra information (which is translated already). ...
Override a value on the serializer with a matching value for the model. Often, the serializer field will point to an underlying model field, which contains extra information (which is translated already). Rather than duplicating this information in the serializer, we can extract it from the mo...
override_value
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/metadata.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/metadata.py
MIT
def get_serializer_info(self, serializer): """Override get_serializer_info so that we can add 'default' values to any fields whose Meta.model specifies a default value.""" self.serializer = serializer request = getattr(self, 'request', None) serializer_info = super().get_serializer_inf...
Override get_serializer_info so that we can add 'default' values to any fields whose Meta.model specifies a default value.
get_serializer_info
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/metadata.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/metadata.py
MIT
def get_field_info(self, field): """Given an instance of a serializer field, return a dictionary of metadata about it. We take the regular DRF metadata and add our own unique flavor """ # Try to add the child property to the dependent field to be used by the super call if self.l...
Given an instance of a serializer field, return a dictionary of metadata about it. We take the regular DRF metadata and add our own unique flavor
get_field_info
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/metadata.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/metadata.py
MIT
def get_token_from_request(request): """Extract token information from a request object.""" auth_keys = ['Authorization', 'authorization'] token_keys = ['token', 'bearer'] for k in auth_keys: if auth_header := request.headers.get(k, None): auth_header = auth_header.strip().lower().s...
Extract token information from a request object.
get_token_from_request
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/middleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/middleware.py
MIT
def check_token(self, request) -> bool: """Check if the user is authenticated via token.""" if token := get_token_from_request(request): # Does the provided token match a valid user? try: token = ApiToken.objects.get(key=token) if token.active and...
Check if the user is authenticated via token.
check_token
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/middleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/middleware.py
MIT
def __call__(self, request): """Check if user needs to be authenticated and is. Redirects to login if not authenticated. """ # Code to be executed for each request before # the view (and later middleware) are called. assert hasattr(request, 'user') # API reques...
Check if user needs to be authenticated and is. Redirects to login if not authenticated.
__call__
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/middleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/middleware.py
MIT
def process_request(self, request): """Check if proxy login is enabled.""" if not settings.REMOTE_LOGIN: return return super().process_request(request)
Check if proxy login is enabled.
process_request
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/middleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/middleware.py
MIT
def process_exception(self, request, exception): """Check if kind is ignored before processing.""" kind, info, data = sys.exc_info() # Check if the error is on the ignore list if kind in settings.IGNORED_ERRORS: return import traceback from django.views.deb...
Check if kind is ignored before processing.
process_exception
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/middleware.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/middleware.py
MIT
def create(self, request, *args, **kwargs): """Override to clean data before processing it.""" serializer = self.get_serializer(data=self.clean_data(request.data)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(seriali...
Override to clean data before processing it.
create
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/mixins.py
MIT
def destroy(self, request, *args, **kwargs): """Custom destroy method to pass kwargs.""" instance = self.get_object() self.perform_destroy(instance, **kwargs) return Response(status=status.HTTP_204_NO_CONTENT)
Custom destroy method to pass kwargs.
destroy
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/mixins.py
MIT
def get_db_instance(self): """Return the instance of the object saved in the database. Returns: object: Instance of the object saved in the database """ if self.pk: try: return self.__class__.objects.get(pk=self.pk) except self.__class...
Return the instance of the object saved in the database. Returns: object: Instance of the object saved in the database
get_db_instance
python
inventree/InvenTree
src/backend/InvenTree/InvenTree/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py
MIT