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 get_field_deltas(self):
"""Return a dict of field deltas.
Compares the current instance with the instance saved in the database,
and returns a dict of fields which have changed.
Returns:
dict: Dict of field deltas
"""
db_instance = self.get_db_instance()... | Return a dict of field deltas.
Compares the current instance with the instance saved in the database,
and returns a dict of fields which have changed.
Returns:
dict: Dict of field deltas
| get_field_deltas | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def run_plugin_validation(self):
"""Throw this model against the plugin validation interface."""
from plugin import PluginMixinEnum, registry
deltas = self.get_field_deltas()
for plugin in registry.with_mixin(PluginMixinEnum.VALIDATION):
try:
if plugin.valid... | Throw this model against the plugin validation interface. | run_plugin_validation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def delete(self):
"""Run plugin validation on model delete.
Allows plugins to prevent model instances from being deleted.
Note: Each plugin may raise a ValidationError to prevent deletion.
"""
from InvenTree.exceptions import log_error
from plugin import PluginMixinEnum... | Run plugin validation on model delete.
Allows plugins to prevent model instances from being deleted.
Note: Each plugin may raise a ValidationError to prevent deletion.
| delete | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_metadata(self, key: str, backup_value=None):
"""Finds metadata for this model instance, using the provided key for lookup.
Args:
key: String key for requesting metadata. e.g. if a plugin is accessing the metadata, the plugin slug should be used
backup_value: Value that s... | Finds metadata for this model instance, using the provided key for lookup.
Args:
key: String key for requesting metadata. e.g. if a plugin is accessing the metadata, the plugin slug should be used
backup_value: Value that should be used if no value is found
Returns:
... | get_metadata | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_reference_pattern(cls):
"""Returns the reference pattern associated with this model.
This is defined by a global setting object, specified by the REFERENCE_PATTERN_SETTING attribute
"""
# By default, we return an empty string
if cls.REFERENCE_PATTERN_SETTING is None:
... | Returns the reference pattern associated with this model.
This is defined by a global setting object, specified by the REFERENCE_PATTERN_SETTING attribute
| get_reference_pattern | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_most_recent_item(cls):
"""Return the item which is 'most recent'.
In practice, this means the item with the highest reference value
"""
query = cls.objects.all().order_by('-reference_int', '-pk')
if query.exists():
return query.first()
return None | Return the item which is 'most recent'.
In practice, this means the item with the highest reference value
| get_most_recent_item | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_next_reference(cls):
"""Return the next available reference value for this particular class."""
# Find the "most recent" item
latest = cls.get_most_recent_item()
if not latest:
# No existing items
return 1
reference = latest.reference.strip
... | Return the next available reference value for this particular class. | get_next_reference | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def generate_reference(cls):
"""Generate the next 'reference' field based on specified pattern."""
# Based on https://stackoverflow.com/a/57570269/14488558
class ReferenceFormatter(Formatter):
def format_field(self, value, format_spec):
if isinstance(value, str) and ... | Generate the next 'reference' field based on specified pattern. | generate_reference | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def validate_reference_pattern(cls, pattern):
"""Ensure that the provided pattern is valid."""
ctx = cls.get_reference_context()
try:
info = InvenTree.format.parse_format_string(pattern)
except Exception as exc:
raise ValidationError({
'value': _(... | Ensure that the provided pattern is valid. | validate_reference_pattern | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def validate_reference_field(cls, value):
"""Check that the provided 'reference' value matches the requisite pattern."""
pattern = cls.get_reference_pattern()
value = str(value).strip()
if len(value) == 0:
raise ValidationError(_('Reference field cannot be empty'))
... | Check that the provided 'reference' value matches the requisite pattern. | validate_reference_field | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def rebuild_reference_field(cls, reference, validate=False):
"""Extract integer out of reference for sorting.
If the 'integer' portion is buried somewhere 'within' the reference,
we can first try to extract it using the pattern.
Example:
reference - BO-123-ABC
pattern -... | Extract integer out of reference for sorting.
If the 'integer' portion is buried somewhere 'within' the reference,
we can first try to extract it using the pattern.
Example:
reference - BO-123-ABC
pattern - BO-{ref}-???
extracted - 123
If we cannot extract usin... | rebuild_reference_field | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def attachments_for_model(self):
"""Return all attachments for this model class."""
from common.models import Attachment
model_type = self.__class__.__name__.lower()
return Attachment.objects.filter(model_type=model_type) | Return all attachments for this model class. | attachments_for_model | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def create_attachment(self, attachment=None, link=None, comment='', **kwargs):
"""Create an attachment / link for this model."""
from common.models import Attachment
kwargs['attachment'] = attachment
kwargs['link'] = link
kwargs['comment'] = comment
kwargs['model_type'] ... | Create an attachment / link for this model. | create_attachment | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def delete(self, delete_children=False, delete_items=False):
"""Handle the deletion of a tree node.
1. Update nodes and items under the current node
2. Delete this node
3. Rebuild the model tree
4. Rebuild the path for any remaining lower nodes
"""
tree_id = self... | Handle the deletion of a tree node.
1. Update nodes and items under the current node
2. Delete this node
3. Rebuild the model tree
4. Rebuild the path for any remaining lower nodes
| delete | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def handle_tree_delete(self, delete_children=False, delete_items=False):
"""Delete a single instance of the tree, based on provided kwargs.
Removing a tree "node" from the database must be considered carefully,
based on what the user intends for any items which exist *under* that node.
... | Delete a single instance of the tree, based on provided kwargs.
Removing a tree "node" from the database must be considered carefully,
based on what the user intends for any items which exist *under* that node.
- "children" are any nodes which exist *under* this node (e.g. PartCategory)
... | handle_tree_delete | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def validate_unique(self, exclude=None):
"""Validate that this tree instance satisfies our uniqueness requirements.
Note that a 'unique_together' requirement for ('name', 'parent') is insufficient,
as it ignores cases where parent=None (i.e. top-level items)
"""
super().validate... | Validate that this tree instance satisfies our uniqueness requirements.
Note that a 'unique_together' requirement for ('name', 'parent') is insufficient,
as it ignores cases where parent=None (i.e. top-level items)
| validate_unique | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def save(self, *args, **kwargs):
"""Custom save method for InvenTreeTree abstract model."""
try:
super().save(*args, **kwargs)
except InvalidMove:
# Provide better error for parent selection
raise ValidationError({'parent': _('Invalid choice')})
# Re-... | Custom save method for InvenTreeTree abstract model. | save | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def getAcceptableParents(self) -> list:
"""Returns a list of acceptable parent items within this model Acceptable parents are ones which are not underneath this item.
Setting the parent of an item to its own child results in recursion.
"""
contents = ContentType.objects.get_for_model(ty... | Returns a list of acceptable parent items within this model Acceptable parents are ones which are not underneath this item.
Setting the parent of an item to its own child results in recursion.
| getAcceptableParents | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_path(self) -> list:
"""Return a list of element in the item tree.
Contains the full path to this item, with each entry containing the following data:
{
pk: <pk>,
name: <name>,
}
"""
return [
{
'pk': item.pk,
... | Return a list of element in the item tree.
Contains the full path to this item, with each entry containing the following data:
{
pk: <pk>,
name: <name>,
}
| get_path | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def delete(self):
"""Custom delete method for InvenTreeNotesMixin.
- Before deleting the object, check if there are any uploaded images associated with it.
- If so, delete the notes first
"""
from common.models import NotesImage
images = NotesImage.objects.filter(
... | Custom delete method for InvenTreeNotesMixin.
- Before deleting the object, check if there are any uploaded images associated with it.
- If so, delete the notes first
| delete | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def barcode_model_type_code(cls):
r"""Return a 'short' code for the model type.
This is used to generate a efficient QR code for the model type.
It is expected to match this pattern: [0-9A-Z $%*+-.\/:]{2}
Note: Due to the shape constrains (45**2=2025 different allowed codes)
th... | Return a 'short' code for the model type.
This is used to generate a efficient QR code for the model type.
It is expected to match this pattern: [0-9A-Z $%*+-.\/:]{2}
Note: Due to the shape constrains (45**2=2025 different allowed codes)
this needs to be explicitly implemented in the m... | barcode_model_type_code | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def format_matched_response(self):
"""Format a standard response for a matched barcode."""
data = {'pk': self.pk}
if hasattr(self, 'get_api_url'):
api_url = self.get_api_url()
data['api_url'] = api_url = f'{api_url}{self.pk}/'
# Attempt to serialize the obje... | Format a standard response for a matched barcode. | format_matched_response | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def assign_barcode(
self, barcode_hash=None, barcode_data=None, raise_error=True, save=True
):
"""Assign an external (third-party) barcode to this object."""
# Must provide either barcode_hash or barcode_data
if barcode_hash is None and barcode_data is None:
raise ValueEr... | Assign an external (third-party) barcode to this object. | assign_barcode | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def unassign_barcode(self):
"""Unassign custom barcode from this model."""
self.barcode_data = ''
self.barcode_hash = ''
self.save() | Unassign custom barcode from this model. | unassign_barcode | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def notify_staff_users_of_error(instance, label: str, context: dict):
"""Helper function to notify staff users of an error."""
import common.models
import common.notifications
try:
# Get all staff users
staff_users = get_user_model().objects.filter(is_staff=True)
target_users =... | Helper function to notify staff users of an error. | notify_staff_users_of_error | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def after_failed_task(sender, instance: Task, created: bool, **kwargs):
"""Callback when a new task failure log is generated."""
from django.conf import settings
max_attempts = int(settings.Q_CLUSTER.get('max_attempts', 5))
n = instance.attempt_count
# Only notify once the maximum number of attemp... | Callback when a new task failure log is generated. | after_failed_task | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def after_error_logged(sender, instance: Error, created: bool, **kwargs):
"""Callback when a server error is logged.
- Send a UI notification to all users with staff status
"""
if created:
try:
url = InvenTree.helpers_model.construct_absolute_url(
reverse(
... | Callback when a server error is logged.
- Send a UI notification to all users with staff status
| after_error_logged | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/models.py | MIT |
def get_model_for_view(view):
"""Attempt to introspect the 'model' type for an API view."""
if hasattr(view, 'get_permission_model'):
return view.get_permission_model()
if hasattr(view, 'serializer_class'):
return view.serializer_class.Meta.model
if hasattr(view, 'get_serializer_class'... | Attempt to introspect the 'model' type for an API view. | get_model_for_view | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def map_scope(
roles: Optional[list[str]] = None,
only_read=False,
read_name=DEFAULT_READ,
map_read: Optional[list[str]] = None,
map_read_name=DEFAULT_READ,
) -> dict:
"""Generate the required scopes for OAS permission views.
Args:
roles (Optional[list[str]]): A list of roles or tab... | Generate the required scopes for OAS permission views.
Args:
roles (Optional[list[str]]): A list of roles or tables to generate granular scopes for.
only_read (bool): If True, only the read scope will be returned for all actions.
read_name (str): The read scope name to use when `only_read` ... | map_scope | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Check if the user has the required scopes or was authenticated another way."""
return self.check_oauth2_authentication(
request, view
) or super().has_permission(request, view) | Check if the user has the required scopes or was authenticated another way. | has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def check_oauth2_authentication(self, request, view):
"""Check if the user is authenticated using OAuth2 and has the required scopes."""
return self.is_oauth2ed(
request
) and TokenMatchesOASRequirements().has_permission(request, view) | Check if the user is authenticated using OAuth2 and has the required scopes. | check_oauth2_authentication | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def is_oauth2ed(self, request):
"""Check if the user is authenticated using OAuth2."""
oauth2authenticated = False
if bool(request.user and request.user.is_authenticated):
oauth2authenticated = isinstance(
request.successful_authenticator, OAuth2Authentication
... | Check if the user is authenticated using OAuth2. | is_oauth2ed | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def get_required_alternate_scopes(self, request, view):
"""Return the required scopes for the current request."""
if hasattr(view, 'required_alternate_scopes'):
return view.required_alternate_scopes
try:
# Extract the model name associated with this request
mo... | Return the required scopes for the current request. | get_required_alternate_scopes | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Determine if the current user has the specified permissions."""
user = request.user
# Superuser can do it all
if user.is_superuser:
return True
# Map the request method to a permission type
rolemap = {**ACTION_MAP,... | Determine if the current user has the specified permissions. | has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Determine if the current user has the specified permissions.
- If the user does have the required role, then allow the request
- If the user does not have the required role, but is authenticated, then allow read-only access
"""
user = ... | Determine if the current user has the specified permissions.
- If the user does have the required role, then allow the request
- If the user does not have the required role, but is authenticated, then allow read-only access
| has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Check if the user is a superuser."""
return bool(
(request.user and request.user.is_superuser)
or request.method in permissions.SAFE_METHODS
) | Check if the user is a superuser. | has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Check if the user is a staff."""
return bool(permissions.IsAuthenticated().has_permission(request, view)) and (
(request.user and request.user.is_staff)
or request.method in permissions.SAFE_METHODS
) | Check if the user is a staff. | has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def auth_exempt(view_func):
"""Mark a view function as being exempt from auth requirements."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.auth_exempt = True
return wraps(view_func)(wrapped_view) | Mark a view function as being exempt from auth requirements. | auth_exempt | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_object_permission(self, request, view, obj):
"""Check if the user that requested is also the object owner."""
try:
user = request.user
except AttributeError: # pragma: no cover
return False
return user == obj.user | Check if the user that requested is also the object owner. | has_object_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def has_permission(self, request, view):
"""Check that the requesting user is 'admin'."""
try:
user = request.user
if request.method in permissions.SAFE_METHODS:
return True
# Any other methods require staff access permissions
return user.... | Check that the requesting user is 'admin'. | has_permission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/permissions.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/permissions.py | MIT |
def isRunningMigrations():
"""Return True if the database is currently running migrations."""
return any(
x in sys.argv
for x in ['migrate', 'makemigrations', 'showmigrations', 'runmigrations']
) | Return True if the database is currently running migrations. | isRunningMigrations | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def isRebuildingData():
"""Return true if any of the rebuilding commands are being executed."""
return any(
x in sys.argv for x in ['rebuild_models', 'rebuild_thumbnails', 'rebuild']
) | Return true if any of the rebuilding commands are being executed. | isRebuildingData | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def isRunningBackup():
"""Return true if any of the backup commands are being executed."""
return any(
x in sys.argv
for x in [
'backup',
'restore',
'dbbackup',
'dbresotore',
'mediabackup',
'mediarestore',
]
) | Return true if any of the backup commands are being executed. | isRunningBackup | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def isGeneratingSchema():
"""Return true if schema generation is being executed."""
if 'schema' in sys.argv:
return True
return any('drf_spectacular' in frame.filename for frame in inspect.stack()) | Return true if schema generation is being executed. | isGeneratingSchema | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def isInServerThread():
"""Returns True if the current thread is a server thread."""
if isInWorkerThread():
return False
if 'runserver' in sys.argv:
return True
return 'gunicorn' in sys.argv[0] | Returns True if the current thread is a server thread. | isInServerThread | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def isInMainThread():
"""Django runserver starts two processes, one for the actual dev server and the other to reload the application.
- The RUN_MAIN env is set in that case. However if --noreload is applied, this variable
is not set because there are no different threads.
"""
if 'runserver' in sys... | Django runserver starts two processes, one for the actual dev server and the other to reload the application.
- The RUN_MAIN env is set in that case. However if --noreload is applied, this variable
is not set because there are no different threads.
| isInMainThread | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def canAppAccessDatabase(
allow_test: bool = False, allow_plugins: bool = False, allow_shell: bool = False
):
"""Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# Prevent datab... | Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
| canAppAccessDatabase | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/ready.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/ready.py | MIT |
def sanitize_svg(
file_data,
strip: bool = True,
elements: str = ALLOWED_ELEMENTS_SVG,
attributes: str = ALLOWED_ATTRIBUTES_SVG,
) -> str:
"""Sanitize a SVG file.
Args:
file_data (str): SVG as string.
strip (bool, optional): Should invalid elements get removed. Defaults to True.... | Sanitize a SVG file.
Args:
file_data (str): SVG as string.
strip (bool, optional): Should invalid elements get removed. Defaults to True.
elements (str, optional): Allowed elements. Defaults to ALLOWED_ELEMENTS_SVG.
attributes (str, optional): Allowed attributes. Defaults to ALLOWED... | sanitize_svg | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sanitizer.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sanitizer.py | MIT |
def get_security_requirement(self, auto_schema):
"""Get the security requirement for the current view."""
ret = super().get_security_requirement(auto_schema)
if ret:
return ret
# If no security requirement is found, try if the view uses our OASTokenMixin
for permissi... | Get the security requirement for the current view. | get_security_requirement | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/schema.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/schema.py | MIT |
def get_operation_id(self) -> str:
"""Custom path handling overrides, falling back to default behavior."""
result_id = super().get_operation_id()
# rename bulk actions to deconflict with single action operation_id
if (self.method == 'DELETE' and self.is_bulk_action('BulkDeleteMixin')) o... | Custom path handling overrides, falling back to default behavior. | get_operation_id | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/schema.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/schema.py | MIT |
def get_operation(
self,
path: str,
path_regex: str,
path_prefix: str,
method: str,
registry: ComponentRegistry,
) -> Optional[_SchemaType]:
"""Custom operation handling, falling back to default behavior."""
operation = super().get_operation(
... | Custom operation handling, falling back to default behavior. | get_operation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/schema.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/schema.py | MIT |
def postprocess_required_nullable(result, generator, request, public):
"""Un-require nullable fields.
Read-only values are all marked as required by spectacular, but InvenTree doesn't always include them in the
response. This removes them from the required list to allow responses lacking read-only nullable... | Un-require nullable fields.
Read-only values are all marked as required by spectacular, but InvenTree doesn't always include them in the
response. This removes them from the required list to allow responses lacking read-only nullable fields to validate
against the schema.
| postprocess_required_nullable | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/schema.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/schema.py | MIT |
def sentry_ignore_errors():
"""Return a list of error types to ignore.
These error types will *not* be reported to sentry.io.
"""
return [
Http404,
MissingRate,
TemplateSyntaxError,
ValidationError,
rest_framework.exceptions.AuthenticationFailed,
rest_fra... | Return a list of error types to ignore.
These error types will *not* be reported to sentry.io.
| sentry_ignore_errors | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sentry.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sentry.py | MIT |
def report_exception(exc):
"""Report an exception to sentry.io."""
if settings.TESTING:
# Skip reporting exceptions in testing mode
return
if settings.SENTRY_ENABLED and settings.SENTRY_DSN:
if not any(isinstance(exc, e) for e in sentry_ignore_errors()):
logger.info('Rep... | Report an exception to sentry.io. | report_exception | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sentry.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sentry.py | MIT |
def get_value(self, data):
"""Test that the returned amount is a valid Decimal."""
amount = super(DecimalField, self).get_value(data)
# Convert an empty string to None
if len(str(amount).strip()) == 0:
amount = None
try:
if amount is not None and amount ... | Test that the returned amount is a valid Decimal. | get_value | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def __init__(self, *args, depends_on, field_serializer, **kwargs):
"""A dependent field can be used to dynamically return child fields based on the value of other fields.
Example:
This example adds two fields. If the client selects integer, an integer field will be shown, but if he
sele... | A dependent field can be used to dynamically return child fields based on the value of other fields.
Example:
This example adds two fields. If the client selects integer, an integer field will be shown, but if he
selects char, an char field will be shown. For any other value, nothing will be sh... | __init__ | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def get_child(self, raise_exception=False):
"""This method tries to extract the child based on the provided data in the request by the client."""
data = deepcopy(self.context['request'].data)
def visit_parent(node):
"""Recursively extract the data for the parent field/serializer in ... | This method tries to extract the child based on the provided data in the request by the client. | get_child | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def visit_parent(node):
"""Recursively extract the data for the parent field/serializer in reverse."""
nonlocal data
if node.parent:
visit_parent(node.parent)
# only do for composite fields and stop right before the current field
if hasattr(n... | Recursively extract the data for the parent field/serializer in reverse. | visit_parent | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def to_internal_value(self, data):
"""This method tries to convert the data to an internal representation based on the defined to_internal_value method on the child."""
self.get_child()
if self.child:
return self.child.to_internal_value(data)
return None | This method tries to convert the data to an internal representation based on the defined to_internal_value method on the child. | to_internal_value | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def to_representation(self, value):
"""This method tries to convert the data to representation based on the defined to_representation method on the child."""
self.get_child()
if self.child:
return self.child.to_representation(value)
return None | This method tries to convert the data to representation based on the defined to_representation method on the child. | to_representation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def __init__(self, instance=None, data=empty, **kwargs):
"""Custom __init__ routine to ensure that *default* values (as specified in the ORM) are used by the DRF serializers, *if* the values are not provided by the user."""
# If instance is None, we are creating a new instance
if instance is Non... | Custom __init__ routine to ensure that *default* values (as specified in the ORM) are used by the DRF serializers, *if* the values are not provided by the user. | __init__ | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def get_initial(self):
"""Construct initial data for the serializer.
Use the 'default' values specified by the django model definition
"""
initials = super().get_initial().copy()
# Are we creating a new instance?
if self.instance is None:
ModelClass = self.M... | Construct initial data for the serializer.
Use the 'default' values specified by the django model definition
| get_initial | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def save(self, **kwargs):
"""Catch any django ValidationError thrown at the moment `save` is called, and re-throw as a DRF ValidationError."""
try:
super().save(**kwargs)
except (ValidationError, DjangoValidationError) as exc:
raise ValidationError(detail=serializers.as_s... | Catch any django ValidationError thrown at the moment `save` is called, and re-throw as a DRF ValidationError. | save | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def create(self, validated_data):
"""Custom create method which supports field adjustment."""
initial_data = validated_data.copy()
# Remove any fields which do not exist on the model
for field in self.skip_create_fields():
initial_data.pop(field, None)
return super(... | Custom create method which supports field adjustment. | create | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def update(self, instance, validated_data):
"""Catch any django ValidationError, and re-throw as a DRF ValidationError."""
try:
instance = super().update(instance, validated_data)
except (ValidationError, DjangoValidationError) as exc:
raise ValidationError(detail=seriali... | Catch any django ValidationError, and re-throw as a DRF ValidationError. | update | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def run_validation(self, data=empty):
"""Perform serializer validation.
In addition to running validators on the serializer fields,
this class ensures that the underlying model is also validated.
"""
# Run any native validation checks first (may raise a ValidationError)
... | Perform serializer validation.
In addition to running validators on the serializer fields,
this class ensures that the underlying model is also validated.
| run_validation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def update(self, instance, validated_data):
"""Overridden update method to re-add the tagmanager."""
to_be_tagged, validated_data = self._pop_tags(validated_data)
tag_object = super().update(instance, validated_data)
for key in to_be_tagged:
# re-add the tagmanager
... | Overridden update method to re-add the tagmanager. | update | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def __init__(self, *args, **kwargs):
"""Remove 'notes' field from list views."""
super().__init__(*args, **kwargs)
if hasattr(self, 'context'):
if view := self.context.get('view', None):
if (
issubclass(view.__class__, ListModelMixin)
... | Remove 'notes' field from list views. | __init__ | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def validate_remote_image(self, url):
"""Perform custom validation for the remote image URL.
- Attempt to download the image and store it against this object instance
- Catches and re-throws any errors
"""
from InvenTree.helpers_model import download_image_from_url
if n... | Perform custom validation for the remote image URL.
- Attempt to download the image and store it against this object instance
- Catches and re-throws any errors
| validate_remote_image | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/serializers.py | MIT |
def get_provider_app(provider):
"""Return the SocialApp object for the given provider."""
from allauth.socialaccount.models import SocialApp
try:
apps = SocialApp.objects.filter(provider__iexact=provider.id)
except SocialApp.DoesNotExist:
logger.warning("SSO SocialApp not found for prov... | Return the SocialApp object for the given provider. | get_provider_app | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sso.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sso.py | MIT |
def check_provider(provider):
"""Check if the given provider is correctly configured.
To be correctly configured, the following must be true:
- Provider must either have a registered SocialApp
- Must have at least one site enabled
"""
import allauth.app_settings
# First, check that the pr... | Check if the given provider is correctly configured.
To be correctly configured, the following must be true:
- Provider must either have a registered SocialApp
- Must have at least one site enabled
| check_provider | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sso.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sso.py | MIT |
def provider_display_name(provider):
"""Return the 'display name' for the given provider."""
if app := get_provider_app(provider):
return app.name
# Fallback value if app not found
return provider.name | Return the 'display name' for the given provider. | provider_display_name | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sso.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sso.py | MIT |
def ensure_sso_groups(sender, sociallogin: SocialLogin, **kwargs):
"""Sync groups from IdP each time a SSO user logs on.
This event listener is registered in the apps ready method.
"""
if not get_global_setting('LOGIN_ENABLE_SSO_GROUP_SYNC'):
return
group_key = get_global_setting('SSO_GROU... | Sync groups from IdP each time a SSO user logs on.
This event listener is registered in the apps ready method.
| ensure_sso_groups | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/sso.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/sso.py | MIT |
def is_worker_running(**kwargs):
"""Return True if the background worker process is operational."""
clusters = Stat.get_all()
if len(clusters) > 0:
return True
"""
Sometimes Stat.get_all() returns [].
In this case we have the 'heartbeat' task running every 5 minutes.
Check to see i... | Return True if the background worker process is operational. | is_worker_running | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/status.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/status.py | MIT |
def check_system_health(**kwargs):
"""Check that the InvenTree system is running OK.
Returns True if all system checks pass.
"""
result = True
if InvenTree.ready.isInTestMode():
# Do not perform further checks if we are running unit tests
return False
if InvenTree.ready.isImpo... | Check that the InvenTree system is running OK.
Returns True if all system checks pass.
| check_system_health | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/status.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/status.py | MIT |
def schedule_task(taskname, **kwargs):
"""Create a scheduled task.
If the task has already been scheduled, ignore!
"""
# If unspecified, repeat indefinitely
repeats = kwargs.pop('repeats', -1)
kwargs['repeats'] = repeats
try:
from django_q.models import Schedule
except AppRegis... | Create a scheduled task.
If the task has already been scheduled, ignore!
| schedule_task | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def check_daily_holdoff(task_name: str, n_days: int = 1) -> bool:
"""Check if a periodic task should be run, based on the provided setting name.
Arguments:
task_name (str): The name of the task being run, e.g. 'dummy_task'
n_days (int): The number of days between task runs (default = 1)
Re... | Check if a periodic task should be run, based on the provided setting name.
Arguments:
task_name (str): The name of the task being run, e.g. 'dummy_task'
n_days (int): The number of days between task runs (default = 1)
Returns:
bool: If the task should be run *now*, or wait another day... | check_daily_holdoff | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def record_task_attempt(task_name: str):
"""Record that a multi-day task has been attempted *now*."""
logger.info("Logging task attempt for '%s'", task_name)
set_global_setting(f'_{task_name}_ATTEMPT', datetime.now().isoformat(), None) | Record that a multi-day task has been attempted *now*. | record_task_attempt | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def offload_task(
taskname, *args, force_async=False, force_sync=False, **kwargs
) -> bool:
"""Create an AsyncTask if workers are running. This is different to a 'scheduled' task, in that it only runs once!
If workers are not running or force_sync flag, is set then the task is ran synchronously.
Retur... | Create an AsyncTask if workers are running. This is different to a 'scheduled' task, in that it only runs once!
If workers are not running or force_sync flag, is set then the task is ran synchronously.
Returns:
bool: True if the task was offloaded (or ran), False otherwise
| offload_task | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def scheduled_task(
interval: str, minutes: Optional[int] = None, tasklist: TaskRegister = None
):
"""Register the given task as a scheduled task.
Example:
```python
@scheduled_task(ScheduledTask.DAILY)
def my_custom_function():
# Perform a custom function once per day
...
`... | Register the given task as a scheduled task.
Example:
```python
@scheduled_task(ScheduledTask.DAILY)
def my_custom_function():
# Perform a custom function once per day
...
```
Args:
interval (str): The interval at which the task should be run
minutes (int, optio... | scheduled_task | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def heartbeat():
"""Simple task which runs at 5 minute intervals, so we can determine that the background worker is actually running.
(There is probably a less "hacky" way of achieving this)?
"""
try:
from django_q.models import OrmQ, Success
except AppRegistryNotReady: # pragma: no cover
... | Simple task which runs at 5 minute intervals, so we can determine that the background worker is actually running.
(There is probably a less "hacky" way of achieving this)?
| heartbeat | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def delete_successful_tasks():
"""Delete successful task logs which are older than a specified period."""
try:
from django_q.models import Success
days = get_global_setting('INVENTREE_DELETE_TASKS_DAYS', 30)
threshold = timezone.now() - timedelta(days=days)
# Delete successful ... | Delete successful task logs which are older than a specified period. | delete_successful_tasks | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def delete_failed_tasks():
"""Delete failed task logs which are older than a specified period."""
try:
from django_q.models import Failure
days = get_global_setting('INVENTREE_DELETE_TASKS_DAYS', 30)
threshold = timezone.now() - timedelta(days=days)
# Delete failed tasks
... | Delete failed task logs which are older than a specified period. | delete_failed_tasks | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def delete_old_error_logs():
"""Delete old error logs from the server."""
try:
from error_report.models import Error
days = get_global_setting('INVENTREE_DELETE_ERRORS_DAYS', 30)
threshold = timezone.now() - timedelta(days=days)
errors = Error.objects.filter(when__lte=threshold... | Delete old error logs from the server. | delete_old_error_logs | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def check_for_updates():
"""Check if there is an update for InvenTree."""
try:
from common.notifications import trigger_superuser_notification
except AppRegistryNotReady: # pragma: no cover
# Apps not yet loaded!
logger.info("Could not perform 'check_for_updates' - App registry not ... | Check if there is an update for InvenTree. | check_for_updates | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def update_exchange_rates(force: bool = False):
"""Update currency exchange rates.
Arguments:
force: If True, force the update to run regardless of the last update time
"""
try:
from djmoney.contrib.exchange.models import Rate
from common.currency import currency_code_default, ... | Update currency exchange rates.
Arguments:
force: If True, force the update to run regardless of the last update time
| update_exchange_rates | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def get_migration_plan():
"""Returns a list of migrations which are needed to be run."""
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
return plan | Returns a list of migrations which are needed to be run. | get_migration_plan | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def check_for_migrations(force: bool = False, reload_registry: bool = True) -> bool:
"""Checks if migrations are needed.
If the setting auto_update is enabled we will start updating.
Returns bool indicating if migrations are up to date
"""
from plugin import registry
def set_pending_migration... | Checks if migrations are needed.
If the setting auto_update is enabled we will start updating.
Returns bool indicating if migrations are up to date
| check_for_migrations | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def set_pending_migrations(n: int):
"""Helper function to inform the user about pending migrations."""
logger.info('There are %s pending migrations', n)
try:
set_global_setting('_PENDING_MIGRATIONS', n, None)
except Exception:
# If the setting cannot be set, we j... | Helper function to inform the user about pending migrations. | set_pending_migrations | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tasks.py | MIT |
def get_template(self, template_name, skip=None):
"""Return a template object for the given template name.
Any custom report or label templates will be forced to reload (without cache).
This ensures that generated PDF reports / labels are always up-to-date.
"""
# List of templat... | Return a template object for the given template name.
Any custom report or label templates will be forced to reload (without cache).
This ensures that generated PDF reports / labels are always up-to-date.
| get_template | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/template.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/template.py | MIT |
def test_allowed_hosts(self):
"""Test that the ALLOWED_HOSTS functions as expected."""
self.assertIn('testserver', settings.ALLOWED_HOSTS)
response = self.client.get('/api/', headers={'host': 'testserver'})
self.assertEqual(response.status_code, 200)
response = self.client.get... | Test that the ALLOWED_HOSTS functions as expected. | test_allowed_hosts | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def preflight(self, url, origin, method='GET'):
"""Make a CORS preflight request to the specified URL."""
headers = {'origin': origin, 'access-control-request-method': method}
return self.client.options(url, headers=headers) | Make a CORS preflight request to the specified URL. | preflight | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_no_origin(self):
"""Test that CORS headers are not included for regular requests.
- We use the /api/ endpoint for this test (it does not require auth)
- By default, in debug mode *all* CORS origins are allowed
"""
# Perform an initial response without the "origin" heade... | Test that CORS headers are not included for regular requests.
- We use the /api/ endpoint for this test (it does not require auth)
- By default, in debug mode *all* CORS origins are allowed
| test_no_origin | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_auth_view(self):
"""Test that CORS requests work for the /auth/ view.
Here, we are not authorized by default,
but the CORS headers should still be included.
"""
url = '/auth/'
# First, a preflight request with a "valid" origin
response = self.preflight... | Test that CORS requests work for the /auth/ view.
Here, we are not authorized by default,
but the CORS headers should still be included.
| test_auth_view | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_cors_regex(self):
"""Test that CORS regexes work as expected."""
valid_urls = [
'http://www.myserver.com',
'http://test.myserver.com',
'http://myserver.com',
'http://www.myserver.com:8080',
]
invalid_urls = [
'http://m... | Test that CORS regexes work as expected. | test_cors_regex | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_prefixes(self):
"""Test inputs where prefixes are used."""
tests = {
'3': 3,
'3m': 3,
'3mm': 0.003,
'3k': 3000,
'3u': 0.000003,
'3 inch': 0.0762,
}
for val, expected in tests.items():
q = InvenT... | Test inputs where prefixes are used. | test_prefixes | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_engineering_units(self):
"""Test that conversion works with engineering notation."""
# Run some basic checks over the helper function
tests = [
('3', '3'),
('3k3', '3.3k'),
('123R45', '123.45R'),
('10n5F', '10.5nF'),
]
for... | Test that conversion works with engineering notation. | test_engineering_units | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_scientific_notation(self):
"""Test that scientific notation is handled correctly."""
tests = [
('3E2', 300),
('-12.3E-3', -0.0123),
('1.23E-3', 0.00123),
('99E9', 99000000000),
]
for val, expected in tests:
output = In... | Test that scientific notation is handled correctly. | test_scientific_notation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_base_units(self):
"""Test conversion to specified base units."""
tests = {
'3': 3,
'3 dozen': 36,
'50 dozen kW': 600000,
'1 / 10': 0.1,
'1/2 kW': 500,
'1/2 dozen kW': 6000,
'0.005 MW': 5000,
}
f... | Test conversion to specified base units. | test_base_units | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_imperial_lengths(self):
"""Test support of imperial length measurements."""
tests = [
('1 inch', 'mm', 25.4),
('1 "', 'mm', 25.4),
('2 "', 'inches', 2),
('3 feet', 'inches', 36),
("3'", 'inches', 36),
("7 '", 'feet', 7),
... | Test support of imperial length measurements. | test_imperial_lengths | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.