2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-06-15 19:45:46 +00:00

fix docstrings 8

This commit is contained in:
Matthias
2022-05-28 03:13:19 +02:00
parent d3d0b76c58
commit d98723160a
6 changed files with 109 additions and 197 deletions

View File

@ -1,5 +1,4 @@
"""
The Part module is responsible for Part management.
"""The Part module is responsible for Part management.
It includes models for:

View File

@ -1,9 +1,4 @@
# -*- coding: utf-8 -*-
"""
This module provides template tags for extra functionality,
over and above the built-in Django tags.
"""
"""This module provides template tags for extra functionality, over and above the built-in Django tags."""
import logging
import os
@ -33,26 +28,22 @@ logger = logging.getLogger('inventree')
@register.simple_tag()
def define(value, *args, **kwargs):
"""
Shortcut function to overcome the shortcomings of the django templating language
"""Shortcut function to overcome the shortcomings of the django templating language
Use as follows: {% define "hello_world" as hello %}
Ref: https://stackoverflow.com/questions/1070398/how-to-set-a-value-of-a-variable-inside-a-template-code
"""
return value
@register.simple_tag(takes_context=True)
def render_date(context, date_object):
"""
Renders a date according to the preference of the provided user
"""Renders a date according to the preference of the provided user
Note that the user preference is stored using the formatting adopted by moment.js,
which differs from the python formatting!
"""
if date_object is None:
return None
@ -106,14 +97,12 @@ def render_date(context, date_object):
@register.simple_tag()
def decimal(x, *args, **kwargs):
"""Simplified rendering of a decimal number"""
return InvenTree.helpers.decimal2string(x)
@register.simple_tag()
def str2bool(x, *args, **kwargs):
"""Convert a string to a boolean value"""
return InvenTree.helpers.str2bool(x)
@ -144,14 +133,12 @@ def to_list(*args):
@register.simple_tag()
def part_allocation_count(build, part, *args, **kwargs):
"""Return the total number of <part> allocated to <build>"""
return InvenTree.helpers.decimal2string(build.getAllocatedQuantity(part))
@register.simple_tag()
def inventree_in_debug_mode(*args, **kwargs):
"""Return True if the server is running in DEBUG mode"""
return djangosettings.DEBUG
@ -166,21 +153,18 @@ def inventree_show_about(user, *args, **kwargs):
@register.simple_tag()
def inventree_docker_mode(*args, **kwargs):
"""Return True if the server is running as a Docker image"""
return djangosettings.DOCKER
@register.simple_tag()
def plugins_enabled(*args, **kwargs):
"""Return True if plugins are enabled for the server instance"""
return djangosettings.PLUGINS_ENABLED
@register.simple_tag()
def inventree_db_engine(*args, **kwargs):
"""Return the InvenTree database backend e.g. 'postgresql'"""
db = djangosettings.DATABASES['default']
engine = db.get('ENGINE', _('Unknown database'))
@ -210,9 +194,7 @@ def inventree_base_url(*args, **kwargs):
@register.simple_tag()
def python_version(*args, **kwargs):
"""
Return the current python version
"""
"""Return the current python version"""
return sys.version.split(' ')[0]
@ -275,7 +257,6 @@ def inventree_github_url(*args, **kwargs):
@register.simple_tag()
def inventree_docs_url(*args, **kwargs):
"""Return URL for InvenTree documenation site"""
tag = version.inventreeDocsVersion()
return f"https://inventree.readthedocs.io/en/{tag}"
@ -295,12 +276,10 @@ def default_currency(*args, **kwargs):
@register.simple_tag()
def setting_object(key, *args, **kwargs):
"""
Return a setting object speciifed by the given key
"""Return a setting object speciifed by the given key
(Or return None if the setting does not exist)
if a user-setting was requested return that
"""
if 'plugin' in kwargs:
# Note, 'plugin' is an instance of an InvenTreePlugin class
@ -319,10 +298,7 @@ def setting_object(key, *args, **kwargs):
@register.simple_tag()
def settings_value(key, *args, **kwargs):
"""
Return a settings value specified by the given key
"""
"""Return a settings value specified by the given key"""
if 'user' in kwargs:
if not kwargs['user'] or (kwargs['user'] and kwargs['user'].is_authenticated is False):
return InvenTreeUserSetting.get_setting(key)
@ -333,37 +309,25 @@ def settings_value(key, *args, **kwargs):
@register.simple_tag()
def user_settings(user, *args, **kwargs):
"""
Return all USER settings as a key:value dict
"""
"""Return all USER settings as a key:value dict"""
return InvenTreeUserSetting.allValues(user=user)
@register.simple_tag()
def global_settings(*args, **kwargs):
"""
Return all GLOBAL InvenTree settings as a key:value dict
"""
"""Return all GLOBAL InvenTree settings as a key:value dict"""
return InvenTreeSetting.allValues()
@register.simple_tag()
def visible_global_settings(*args, **kwargs):
"""
Return any global settings which are not marked as 'hidden'
"""
"""Return any global settings which are not marked as 'hidden'"""
return InvenTreeSetting.allValues(exclude_hidden=True)
@register.simple_tag()
def progress_bar(val, max_val, *args, **kwargs):
"""
Render a progress bar element
"""
"""Render a progress bar element"""
item_id = kwargs.get('id', 'progress-bar')
val = InvenTree.helpers.normalize(val)
@ -428,10 +392,7 @@ def get_user_color_theme(username):
@register.simple_tag()
def get_available_themes(*args, **kwargs):
"""
Return the available theme choices
"""
"""Return the available theme choices"""
themes = []
for key, name in ColorTheme.get_color_themes_choices():
@ -445,13 +406,11 @@ def get_available_themes(*args, **kwargs):
@register.simple_tag()
def primitive_to_javascript(primitive):
"""
Convert a python primitive to a javascript primitive.
"""Convert a python primitive to a javascript primitive.
e.g. True -> true
'hello' -> '"hello"'
"""
if type(primitive) is bool:
return str(primitive).lower()
@ -465,10 +424,9 @@ def primitive_to_javascript(primitive):
@register.filter
def keyvalue(dict, key):
"""
access to key of supplied dict
"""Access to key of supplied dict
usage:
Usage:
{% mydict|keyvalue:mykey %}
"""
return dict.get(key)
@ -476,10 +434,9 @@ def keyvalue(dict, key):
@register.simple_tag()
def call_method(obj, method_name, *args):
"""
enables calling model methods / functions from templates with arguments
"""Enables calling model methods / functions from templates with arguments
usage:
Usage:
{% call_method model_object 'fnc_name' argument1 %}
"""
method = getattr(obj, method_name)
@ -489,7 +446,6 @@ def call_method(obj, method_name, *args):
@register.simple_tag()
def authorized_owners(group):
"""Return authorized owners"""
owners = []
try:
@ -508,7 +464,6 @@ def authorized_owners(group):
@register.simple_tag()
def object_link(url_name, pk, ref):
"""Return highlighted link to object"""
ref_url = reverse(url_name, kwargs={'pk': pk})
return mark_safe('<b><a href="{}">{}</a></b>'.format(ref_url, ref))
@ -522,24 +477,23 @@ def mail_configured():
@register.simple_tag()
def inventree_customize(reference, *args, **kwargs):
"""Return customization values for the user interface"""
return djangosettings.CUSTOMIZE.get(reference, '')
@register.simple_tag()
def inventree_logo(*args, **kwargs):
"""Return the path to the logo-file"""
if settings.CUSTOM_LOGO:
return default_storage.url(settings.CUSTOM_LOGO)
return static('img/inventree.png')
class I18nStaticNode(StaticNode):
"""Custom StaticNode
Replaces a variable named *lng* in the path with the current language
"""
custom StaticNode
replaces a variable named *lng* in the path with the current language
"""
def render(self, context): # pragma: no cover
self.original = getattr(self, 'original', None)
@ -561,17 +515,16 @@ if settings.DEBUG:
@register.simple_tag()
def i18n_static(url_name):
""" simple tag to enable {% url %} functionality instead of {% static %} """
"""Simple tag to enable {% url %} functionality instead of {% static %}"""
return reverse(url_name)
else: # pragma: no cover
@register.tag('i18n_static')
def do_i18n_static(parser, token):
"""
Overrides normal static, adds language - lookup for prerenderd files #1485
"""Overrides normal static, adds language - lookup for prerenderd files #1485
usage (like static):
Usage (like static):
{% i18n_static path [as varname] %}
"""
bits = token.split_contents()

View File

@ -1,6 +1,4 @@
"""
Provide templates for the various model status codes.
"""
"""Provide templates for the various model status codes."""
from django import template
from django.utils.safestring import mark_safe

View File

@ -1,11 +1,9 @@
"""
URL lookup for Part app. Provides URL endpoints for:
"""URL lookup for Part app. Provides URL endpoints for:
- Display / Create / Edit / Delete PartCategory
- Display / Create / Edit / Delete Part
- Create / Edit / Delete PartAttachment
- Display / Create / Edit / Delete SupplierPart
"""
from django.urls import include, re_path

View File

@ -1,6 +1,4 @@
"""
Django views for interacting with Part app
"""
"""Django views for interacting with Part app"""
import io
import os
@ -43,8 +41,7 @@ from .models import (Part, PartCategory, PartCategoryParameterTemplate,
class PartIndex(InvenTreeRoleMixin, ListView):
""" View for displaying list of Part objects
"""
"""View for displaying list of Part objects"""
model = Part
template_name = 'part/category.html'
@ -146,7 +143,7 @@ class PartSetCategory(AjaxUpdateView):
class PartImport(FileManagementFormView):
''' Part: Upload file, match to fields and import parts(using multi-Step form) '''
"""Part: Upload file, match to fields and import parts(using multi-Step form)"""
permission_required = 'part.add'
class PartFileManager(FileManager):
@ -354,8 +351,7 @@ class PartImportAjax(FileManagementAjaxView, PartImport):
class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView):
""" Detail view for Part object
"""
"""Detail view for Part object"""
context_object_name = 'part'
queryset = Part.objects.all().select_related('category')
@ -364,9 +360,7 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView):
# Add in some extra context information based on query params
def get_context_data(self, **kwargs):
"""
Provide extra context data to template
"""
"""Provide extra context data to template"""
context = super().get_context_data(**kwargs)
part = self.get_object()
@ -396,7 +390,7 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView):
return self.get_object()
def get_pricing(self, quantity=1, currency=None):
""" returns context with pricing information """
"""Returns context with pricing information"""
ctx = PartPricing.get_pricing(self, quantity, currency)
part = self.get_part()
default_currency = inventree_settings.currency_code_default()
@ -503,7 +497,7 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView):
return ctx
def get_initials(self):
""" returns initials for form """
"""Returns initials for form"""
return {'quantity': self.get_quantity()}
def post(self, request, *args, **kwargs):
@ -559,7 +553,6 @@ class PartQRCode(QRCodeView):
def get_qr_data(self):
"""Generate QR code data for the Part"""
try:
part = Part.objects.get(id=self.pk)
return part.format_barcode()
@ -568,9 +561,7 @@ class PartQRCode(QRCodeView):
class PartImageDownloadFromURL(AjaxUpdateView):
"""
View for downloading an image from a provided URL
"""
"""View for downloading an image from a provided URL"""
model = Part
@ -579,12 +570,10 @@ class PartImageDownloadFromURL(AjaxUpdateView):
ajax_form_title = _('Download Image')
def validate(self, part, form):
"""
Validate that the image data are correct.
"""Validate that the image data are correct.
- Try to download the image!
"""
# First ensure that the normal validation routines pass
if not form.is_valid():
return
@ -628,10 +617,7 @@ class PartImageDownloadFromURL(AjaxUpdateView):
return
def save(self, part, form, **kwargs):
"""
Save the downloaded image to the part
"""
"""Save the downloaded image to the part"""
fmt = self.image.format
if not fmt:
@ -698,8 +684,8 @@ class BomUpload(InvenTreeRoleMixin, DetailView):
class BomUploadTemplate(AjaxView):
"""
Provide a BOM upload template file for download.
"""Provide a BOM upload template file for download.
- Generates a template file in the provided format e.g. ?format=csv
"""
@ -711,8 +697,8 @@ class BomUploadTemplate(AjaxView):
class BomDownload(AjaxView):
"""
Provide raw download of a BOM file.
"""Provide raw download of a BOM file.
- File format should be passed as a query param e.g. ?format=csv
"""
@ -804,7 +790,7 @@ class PartPricing(AjaxView):
return None
def get_pricing(self, quantity=1, currency=None):
""" returns context with pricing information """
"""Returns context with pricing information"""
if quantity <= 0:
quantity = 1
@ -898,7 +884,7 @@ class PartPricing(AjaxView):
return ctx
def get_initials(self):
""" returns initials for form """
"""Returns initials for form"""
return {'quantity': self.get_quantity()}
def get(self, request, *args, **kwargs):
@ -931,9 +917,7 @@ class PartPricing(AjaxView):
class PartParameterTemplateCreate(AjaxCreateView):
"""
View for creating a new PartParameterTemplate
"""
"""View for creating a new PartParameterTemplate"""
model = PartParameterTemplate
form_class = part_forms.EditPartParameterTemplateForm
@ -941,9 +925,7 @@ class PartParameterTemplateCreate(AjaxCreateView):
class PartParameterTemplateEdit(AjaxUpdateView):
"""
View for editing a PartParameterTemplate
"""
"""View for editing a PartParameterTemplate"""
model = PartParameterTemplate
form_class = part_forms.EditPartParameterTemplateForm
@ -990,9 +972,7 @@ class CategoryDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView):
class CategoryDelete(AjaxDeleteView):
"""
Delete view to delete a PartCategory
"""
"""Delete view to delete a PartCategory"""
model = PartCategory
ajax_template_name = 'part/category_delete.html'
@ -1032,7 +1012,6 @@ class CategoryParameterTemplateCreate(AjaxCreateView):
- Hide the 'category' field (parent part)
- Display parameter templates which are not yet related
"""
form = super().get_form()
form.fields['category'].widget = HiddenInput()
@ -1069,7 +1048,6 @@ class CategoryParameterTemplateCreate(AjaxCreateView):
- If the add_to_same_level_categories object is set, link parameter template to
same level categories
"""
form = self.get_form()
valid = form.is_valid()

View File

@ -6,10 +6,7 @@ import plugin.registry as pl_registry
def plugin_update(queryset, new_status: bool):
"""
General function for bulk changing plugins
"""
"""General function for bulk changing plugins"""
apps_changed = False
# Run through all plugins in the queryset as the save method needs to be overridden
@ -26,25 +23,18 @@ def plugin_update(queryset, new_status: bool):
@admin.action(description='Activate plugin(s)')
def plugin_activate(modeladmin, request, queryset):
"""
Activate a set of plugins
"""
"""Activate a set of plugins"""
plugin_update(queryset, True)
@admin.action(description='Deactivate plugin(s)')
def plugin_deactivate(modeladmin, request, queryset):
"""
Deactivate a set of plugins
"""
"""Deactivate a set of plugins"""
plugin_update(queryset, False)
class PluginSettingInline(admin.TabularInline):
"""
Inline admin class for PluginSetting
"""
"""Inline admin class for PluginSetting"""
model = models.PluginSetting
@ -57,9 +47,7 @@ class PluginSettingInline(admin.TabularInline):
class PluginConfigAdmin(admin.ModelAdmin):
"""
Custom admin with restricted id fields
"""
"""Custom admin with restricted id fields"""
readonly_fields = ["key", "name", ]
list_display = ['name', 'key', '__str__', 'active', ]
@ -69,9 +57,7 @@ class PluginConfigAdmin(admin.ModelAdmin):
class NotificationUserSettingAdmin(admin.ModelAdmin):
"""
Admin class for NotificationUserSetting
"""
"""Admin class for NotificationUserSetting"""
model = models.NotificationUserSetting