shuup.utils package

Submodules

shuup.utils.analog module

class shuup.utils.analog.LogEntryKind[source]

Bases: enumfields.enums.Enum

An enumeration.

OTHER = 0
AUDIT = 1
EDIT = 2
DELETION = 3
NOTE = 4
EMAIL = 5
WARNING = 6
ERROR = 7
class shuup.utils.analog.BaseLogEntry(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Parameters:
  • created_on (DateTimeField) – Created on
  • user (ForeignKey to django.contrib.auth.models.User) – User
  • message (CharField) – Message
  • identifier (CharField) – Identifier
  • kind (EnumIntegerField) – Log entry kind
  • extra (JSONField) – Extra data
target = None
created_on

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

message

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

identifier

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

kind

A property descriptor which ensures that field.to_python() is called on _every_ assignment to the field.

This used to be provided by the django.db.models.subclassing.Creator class, which in turn was used by the deprecated-in-Django-1.10 SubfieldBase class, hence the reimplementation here.

extra

A placeholder class that provides a way to set the attribute on the model.

class Meta[source]

Bases: object

abstract = False
get_kind_display(*, field=<enumfields.fields.EnumIntegerField: kind>)
get_next_by_created_on(*, field=<django.db.models.fields.DateTimeField: created_on>, is_next=True, **kwargs)
get_previous_by_created_on(*, field=<django.db.models.fields.DateTimeField: created_on>, is_next=False, **kwargs)
user_id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

shuup.utils.analog.define_log_model(model_class)[source]

shuup.utils.babel_precision_provider module

shuup.utils.babel_precision_provider.get_precision(currency)[source]

Get precisision for given currency from Babel.

Parameters:currency (str) – Currency code as 3-letter string (ISO-4217)
Return type:decimal.Decimal
Returns:Precision value for given currency code

shuup.utils.dates module

shuup.utils.dates.parse_date(value)[source]

Tries to make a date out of the value. If impossible, it raises an exception.

Parameters:value – A value of some kind.
Returns:Date
Return type:datetime.date
Raises:ValueError
shuup.utils.dates.parse_time(value)[source]

Tries to make a time out of the value. If impossible, it raises an exception.

Parameters:value – A value of some kind.
Returns:Time.
Return type:datetime.time
Raises:ValueError
shuup.utils.dates.try_parse_datetime(value)[source]

Tries to make a datetime out of the value. If impossible, returns None.

Parameters:value – A value of some kind.
Returns:Datetime.
Return type:datetime.datetime
shuup.utils.dates.try_parse_date(value)[source]

Tries to make a time out of the value. If impossible, returns None.

Parameters:value – A value of some kind.
Returns:Date.
Return type:datetime.date
shuup.utils.dates.try_parse_time(value)[source]

Tries to make a time out of the value. If impossible, returns None.

Parameters:value – A value of some kind.
Returns:Time.
Return type:datetime.time

shuup.utils.decorators module

shuup.utils.decorators.non_reentrant(func)[source]

shuup.utils.deprecation module

exception shuup.utils.deprecation.RemovedInShuup20Warning[source]

Bases: PendingDeprecationWarning

exception shuup.utils.deprecation.RemovedFromShuupWarning[source]

Bases: DeprecationWarning

shuup.utils.deprecation.RemovedInFutureShuupWarning

alias of RemovedInShuup20Warning

shuup.utils.django_compat module

shuup.utils.django_compat.is_anonymous(user)[source]
shuup.utils.django_compat.is_authenticated(user)[source]
shuup.utils.django_compat.get_middleware_classes()[source]

shuup.utils.djangoenv module

shuup.utils.djangoenv.has_installed(app)[source]

Returns whether the app is installed in Django, it means, it is in INSTALLED_APPS settings

Parameters:app (str) – the application identifier like shuup.front

shuup.utils.excs module

exception shuup.utils.excs.Problem(message, title=None)[source]

Bases: Exception

User-visible exception.

message

Append a link to this Problem and return itself.

This API is designed after Exception.with_traceback(), so you can fluently chain this in a raise statement:

raise Problem("Oops").with_link("...", "...")
Parameters:
  • url (str) – URL string.
  • title (str) – Title text.
Returns:

This same Problem.

Return type:

shuup.utils.excs.Problem

exception shuup.utils.excs.ExceptionalResponse(response)[source]

Bases: Exception

shuup.utils.excs.extract_messages(obj_list)[source]

Extract “messages” from a list of exceptions or other objects.

For ValidationErrors, messages are flattened into the output. For Exceptions, args[0] is added into the output. For other objects, force_text is called.

Parameters:obj_list (Iterable[object]) – List of exceptions etc.
Return type:Iterable[str]

shuup.utils.fields module

class shuup.utils.fields.RelaxedModelChoiceField(queryset, *, empty_label='---------', required=True, widget=None, label=None, initial=None, help_text='', to_field_name=None, limit_choices_to=None, **kwargs)[source]

Bases: django.forms.models.ModelChoiceField

to_python(value)[source]
class shuup.utils.fields.TypedMultipleChoiceWithLimitField(min_limit=None, max_limit=None, **kwargs)[source]

Bases: django.forms.fields.TypedMultipleChoiceField

clean(value)[source]

shuup.utils.filer module

shuup.utils.filer.file_size_validator(value)[source]
class shuup.utils.filer.UploadFileForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None)[source]

Bases: django.forms.forms.Form

base_fields = OrderedDict([('file', <django.forms.fields.FileField object>)])
declared_fields = OrderedDict([('file', <django.forms.fields.FileField object>)])
media
class shuup.utils.filer.UploadImageForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None)[source]

Bases: django.forms.forms.Form

base_fields = OrderedDict([('file', <django.forms.fields.ImageField object>)])
declared_fields = OrderedDict([('file', <django.forms.fields.ImageField object>)])
media
shuup.utils.filer.filer_folder_from_path(path)[source]

Split path by slashes and create a hierarchy of Filer Folder objects accordingly. Blank path components are ignored, so “/////foo//////bar///” is the same as “foo/bar”.

The empty string (and None) are handled as “no folder”, i.e. root folder.

Parameters:path (str|None) – Pathname or None.
Returns:Folder.
Return type:filer.models.Folder
shuup.utils.filer.filer_file_from_upload(request, path, upload_data, sha1=None)[source]

Create a filer.models.filemodels.File from an upload (UploadedFile or such). If the sha1 parameter is passed and a file with said SHA1 is found, it will be returned instead.

Parameters:
  • request (django.http.request.HttpRequest|None) – Request, to figure out the owner for this file.
  • path (basestring|filer.models.Folder) – Pathname string (see filer_folder_from_path) or a Filer Folder.
  • upload_data (django.core.files.base.File) – Upload data.
  • sha1 (basestring) – SHA1 checksum. If given and a matching model with the SHA1 is found, it is returned instead.
Return type:

filer.models.filemodels.File

shuup.utils.filer.filer_image_from_upload(request, path, upload_data, sha1=None)[source]

Create a Filer Image from an upload (UploadedFile or such). If the sha1 parameter is passed and an Image with said SHA1 is found, it will be returned instead.

Parameters:
  • request (django.http.request.HttpRequest|None) – Request, to figure out the owner for this file.
  • path (basestring|filer.models.Folder) – Pathname string (see filer_folder_from_path) or a Filer Folder.
  • upload_data (django.core.files.base.File) – Upload data.
  • sha1 (basestring) – SHA-1 checksum of the data, if available, to do deduplication.
Return type:

filer.models.imagemodels.Image

shuup.utils.filer.filer_image_from_data(request, path, file_name, file_data, sha1=None)[source]

Create a Filer Image from the given data string. If the sha1 parameter is passed and True (the value True, not a truey value), the SHA-1 of the data string is calculated and passed to the underlying creation function. If the sha1 parameter is truthy (generally the SHA-1 hex string), it’s passed directly to the creation function.

Parameters:
  • request (django.http.request.HttpRequest|None) – Request, to figure out the owner for this file.
  • path (basestring|filer.models.Folder) – Pathname string (see filer_folder_from_path) or a Filer Folder.
  • file_name – File name.
  • file_data (bytes) – Upload data.
  • sha1 (basestring|bool) – SHA-1 checksum of the data, if available, to do deduplication. May also be True to calculate the SHA-1 first.
Return type:

filer.models.imagemodels.Image

shuup.utils.filer.filer_file_to_json_dict(file, user=None)[source]
Return type:dict
shuup.utils.filer.filer_folder_to_json_dict(folder, children=None, user=None)[source]
Return type:dict
shuup.utils.filer.subfolder_of_users_root(user, folder)[source]
shuup.utils.filer.ensure_media_folder(shop, folder)[source]
shuup.utils.filer.ensure_media_file(shop, file)[source]
shuup.utils.filer.get_or_create_folder(shop, path, user=None)[source]
shuup.utils.filer.can_see_root_folder(user)[source]

Return True if the user is allowed to see files that exists in the root folder. This means all files that have folder=None.

shuup.utils.form_group module

exception shuup.utils.form_group.FormInstantiationAttributeError[source]

Bases: Exception

AttributeErrors occurring within the forms property are transmogrified into these.

class shuup.utils.form_group.FormDef(name, form_class, required=True, kwargs=None)[source]

Bases: object

instantiate(prefix, group_initial=None, **extra_kwargs)[source]
class shuup.utils.form_group.FormGroup(data=None, files=None, auto_id='id_%s', prefix=None, initial=None)[source]

Bases: object

add_form_def(name, form_class, required=True, kwargs=None)[source]
instantiate_forms()[source]
forms
full_clean()[source]
errors

Returns an ErrorDict for the data provided for the form

is_valid()[source]

shuup.utils.forms module

shuup.utils.forms.merged_initial_and_data(form)[source]
shuup.utils.forms.get_effective_form_data(form)[source]

Return ‘effective’ data for the form, in essence running its validation methods, but trying to return its state to what it was before the full_clean. Not fool- proof, but what in this universe is.

Returns:data dict
shuup.utils.forms.fill_model_instance(instance, data)[source]

Fill whatever fields possible in instance using the data dict. :param instance: :param data:

shuup.utils.http module

shuup.utils.http.get_client_ip(request)[source]
shuup.utils.http.retry_request(n_retries=5, **kwargs)[source]

Retry a requests request with exponential backoff up to n_retries times.

Parameters:
  • n_retries (int) – Maximum retries
  • kwargs – Kwargs to pass to requests.request().
Returns:

Requests response.

Return type:

requests.Response

shuup.utils.i18n module

shuup.utils.i18n.lang_lru_cache(func)[source]

Language aware least recently used cache decorator

shuup.utils.i18n.get_babel_locale[source]

Parse a Django-format (dash-separated) locale string and return a Babel locale.

This function is decorated with lru_cache, so executions should be cheap even if babel.Locale.parse() most definitely is not.

Parameters:locale_string (str) – A locale string (“en-US”, “fi-FI”, “fi”)
Returns:Babel Locale
Return type:babel.Locale
shuup.utils.i18n.get_current_babel_locale(fallback='en-US-POSIX')[source]

Get a Babel locale based on the thread’s locale context.

Parameters:fallback – Locale to fallback to; set to None to raise an exception instead.
Returns:Babel Locale
Return type:babel.Locale
shuup.utils.i18n.format_number(value, digits=None)[source]
shuup.utils.i18n.format_percent(value, digits=0)[source]
shuup.utils.i18n.get_locally_formatted_datetime(datetime)[source]

Return a formatted, localized version of datetime based on the current context.

shuup.utils.i18n.format_money(amount, digits=None, widen=0, locale=None)[source]

Format a Money object in the given locale.

If neither digits or widen is passed, the preferred number of digits for the amount’s currency is used.

Parameters:
  • amount (Money) – The Money object to format
  • digits (int|None) – How many digits to format the currency with.
  • widen (int|None) – How many digits to widen any existing decimal width with.
  • locale (Locale|str) – Locale object or locale identifier
Returns:

Formatted string

Return type:

str

shuup.utils.i18n.get_language_name(language_code)[source]

Get a language’s name in the currently active locale.

Parameters:language_code (str) – Language code (possibly with an added script suffix (zh_Hans, zh-Hans))
Returns:The language name, or the code if the language couldn’t be derived.
Return type:str
shuup.utils.i18n.javascript_catalog_all(request, domain='djangojs')[source]

Get JavaScript message catalog for all apps in INSTALLED_APPS.

shuup.utils.i18n.get_currency_name(currency)[source]
shuup.utils.i18n.is_existing_language(language_code)[source]

Try to find out if the language actually exists.

Calling babel.Locale("en").languages.keys() will contain extinct languages. :param language_code: A language code string (“fi”, “en”) :type language_code: str :return: True or False :rtype: bool

shuup.utils.i18n.remove_extinct_languages[source]

shuup.utils.importing module

shuup.utils.importing.load(specification, context_explanation='Load')[source]
shuup.utils.importing.clear_load_cache()[source]
shuup.utils.importing.cached_load(setting_name, default_value=None)[source]

shuup.utils.iterables module

shuup.utils.iterables.first(iterable, default=None)[source]

Get the first item from the iterable, if possible, or return default.

The iterable is, naturally, iterated for one value.

Parameters:
  • iterable (Iterable) – An iterable.
  • default (object) – Default value
Returns:

The first item from the iterable, or default

Return type:

object

shuup.utils.iterables.batch(iterable, count)[source]

Yield batches of count items from the given iterable.

>>> tuple(x for x in batch([1, 2, 3, 4, 5, 6, 7], 3))
([1, 2, 3], [4, 5, 6], [7])
Parameters:
  • iterable (Iterable) – An iterable
  • count (int) – Number of items per batch. If <= 0, nothing is yielded.
Returns:

Iterable of lists of items

Return type:

Iterable[list[object]]

shuup.utils.migrations module

shuup.utils.migrations.get_managers_for_migration()[source]

shuup.utils.models module

shuup.utils.models.get_data_dict(obj, force_text_for_value=False)[source]
shuup.utils.models.copy_model_instance(obj)[source]

shuup.utils.money module

class shuup.utils.money.Money[source]

Bases: shuup.utils.numbers.UnittedDecimal

Money value with currency.

The pure decimal value is available from the base classes value property (preferred way) or by casting to Decimal.

Money objects with different currencies cannot be compared or calculated with and will raise UnitMixupError.

See __new__.

Create new Money instance with given value and currency.

If no currency is given explicitly and value has a property named currency, then that will be used. Otherwise currency is a required argument and not passing one will raise a TypeError.

Parameters:
  • value (str|numbers.Number) – Value as string or number.
  • currency (str|None) – Currency as ISO-4217 code (3-letter string) or None.
classmethod from_data(value, currency)[source]
unit_matches_with(other)[source]
new(value)[source]
as_rounded(digits=None, rounding='ROUND_HALF_EVEN')[source]

Get rounded value of self.

Return the value rounded to given digits if specified, otherwise to the precision of self.currency as returned by the precision provider, see set_precision_provider.

Parameters:
  • digits (int|None) – Number of digits to round to or None.
  • rounding (str) – Rounding mode to use.
Return type:

Money

Returns:

A new Money instance with the rounded value.

shuup.utils.money.set_precision_provider(precision_provider)[source]

Set precision provider for Money instances.

Default precision provider is shuup.utils.babel_precision_provider.get_precision.

Parameters:precision_provider (Callable[[str], decimal.Decimal|None]) – Function which will return precision for given currency code, or None for unhandled currency codes, e.g. func('USD') could return Decimal('0.01').

shuup.utils.mptt module

shuup.utils.mptt.get_cached_trees(queryset)[source]

Takes a list/queryset of model objects in MPTT left (depth-first) order and caches the children and parent on each node. This allows up and down traversal through the tree without the need for further queries. Use cases include using a recursively included template or arbitrarily traversing trees.

NOTE: nodes _must_ be passed in the correct (depth-first) order. If they aren’t, a ValueError will be raised.

Returns a list of top-level nodes. If a single tree was provided in its entirety, the list will of course consist of just the tree’s root node.

For filtered querysets, if no ancestors for a node are included in the queryset, it will appear in the returned list as a top-level node.

Aliases to this function are also available:

mptt.templatetags.mptt_tag.cache_tree_children
Use for recursive rendering in templates.
mptt.querysets.TreeQuerySet.get_cached_trees
Useful for chaining with queries; e.g., Node.objects.filter(**kwargs).get_cached_trees()

FIXME: This method fixed the original mptt.utils.get_cached_trees method as it doesn’t consider filtered querysets that might not contain all tree nodes.

shuup.utils.multilanguage_model_form module

shuup.utils.multilanguage_model_form.to_language_codes(languages, default_language)[source]
class shuup.utils.multilanguage_model_form.MultiLanguageModelForm(**kwargs)[source]

Bases: parler.forms.TranslatableModelForm

base_fields = OrderedDict()
clean()[source]

Avoid partially translated languages where the translated fields that are required are not set.

save(commit=True)[source]
pre_master_save(instance)[source]
declared_fields = OrderedDict()
media

shuup.utils.numbers module

shuup.utils.numbers.bankers_round(value, ndigits=0)[source]
shuup.utils.numbers.strip_non_float_chars(s)[source]

Strips characters that aren’t part of normal floats.

shuup.utils.numbers.parse_decimal_string(s)[source]

Parse decimals with “best effort”.

Parses a string (or unicode) that may be embellished with spaces and other weirdness into the most probable Decimal.

>>> assert parse_decimal_string('42') == Decimal(42)
>>> assert parse_decimal_string('0') == Decimal(0)
>>> assert parse_decimal_string('3.5') == Decimal('3.5')
>>> assert parse_decimal_string('') == Decimal(0)
>>> assert parse_decimal_string(3.5) == Decimal('3.5')
>>> assert parse_decimal_string(-5) == Decimal(-5)
>>> assert parse_decimal_string('1e12') == Decimal(112)
>>> assert parse_decimal_string(float('inf')) == Decimal('inf')
Parameters:s (str) – Input value
Returns:Decimal
Return type:Decimal
shuup.utils.numbers.try_parse_decimal_string(s)[source]
shuup.utils.numbers.get_string_sort_order(s)[source]

Return a sorting order value for a string that contains a garment size.

Parameters:s (str) – Input value (string or number)
Returns:Sorting tuple
Return type:tuple
class shuup.utils.numbers.UnittedDecimal

Bases: decimal.Decimal

Decimal with unit.

Allows creating decimal classes that cannot be mixed, e.g. to prevent operations like:

TaxfulPrice(1) + TaxlessPrice(2)

where TaxfulPrice and TaxlessPrice are subclasses of UnittedDecimal.

copy_negate(*args, **kwargs)[source]
new(value)[source]

Create new instance with given value using same unit as self.

Post-condition: If x = y.new(v), then x.unit_matches_with(y) and x.value == v.

Returns:Object with same type as self and matching unit, but with given decimal value.
Return type:UnittedDecimal
quantize(exp, *args, **kwargs)[source]
unit_matches_with(other)[source]

Test if self and other have matching units.

Return type:bool
value

Value of this decimal without the unit.

Return type:decimal.Decimal
exception shuup.utils.numbers.UnitMixupError(obj1, obj2, msg='Unit mixup')

Bases: TypeError

Invoked operation for UnittedDecimal and object with non-matching unit.

The objects involved are stored in instance variables obj1 and obj2. Former is instance of UnittedDecimal or its subclass and the other could be any object.

Variables:
  • obj1 (UnittedDecimal) – Involved object 1.
  • obj2 (Any) – Involved object 2.

shuup.utils.objects module

shuup.utils.objects.extract_inner_value(source, attr_chain)[source]

Search for a stored value by recursing through dict keys and attributes. Erroneous/missing keys/attribute names will return None.

Parameters:
  • source – The original object, that either has attributes or is itself a dict.
  • attr_chain (tuple) – A tuple of properly ordered strings, containing the attributes and/or keys to successively obtain.
>>> mydict = {"foo": {"bar": {"thing": 25}}}
>>> extract_inner_value(mydict, ("foo", "bar", "thing"))
25
>>> extract_inner_value(mydict, ("foo", "bar", "unthing"))
>>> bool(extract_inner_value(mydict, ("__getitem__",)))
True
>>> bool(extract_inner_value(mydict, ("__getotem__",)))
False
shuup.utils.objects.compare_partial_dicts(source, comparee)[source]

Compare dicts in a “partial” manner. All key/value pairs in source must exist and be equal to those in comparee.

This differs from a raw == in that keys that do not exist in source may exist in comparee.

Parameters:
  • source (dict) – source dict
  • comparee (dict) – comparee dict
Return type:

bool

Returns:

True or False

shuup.utils.objects.compact(in_obj, none_only=True, deep=True)[source]

Compact iterable by removing falsy values.

Iterable may be a mapping or a list.

By default uses not value to test for falseness, but if none_only is set, will use value is None.

By default, iterables within the iterable are also compacted. This can be controlled by the deep argument.

Parameters:
  • in_obj (Iterable) – The object to compact
  • none_only (bool) – Remove only Nones
  • deep (bool) – Recurse through iterables within in_obj
Returns:

Flattened iterable

Return type:

list|dict

shuup.utils.patterns module

class shuup.utils.patterns.Pattern(pattern_text)[source]

Bases: object

Compile a pattern from the given pattern_text.

Patterns are comma-separated atoms of the forms:

  • * – matches anything
  • text – matched directly
  • min-max – inclusive range matched lexicographically OR as integers if possible
  • wild* – wildcards (asterisks and question marks allowed)

In addition, atoms may be prefixed with to negate them.

For instance, “10-20,!15” would match all strings (or numbers) between 10 and 20, but not 15.

matches(target)[source]

Evaluate this Pattern against the target.

Return type:bool
get_alphabetical_limits()[source]
as_normalized()[source]

Return the pattern’s source text in a “normalized” form.

Return type:str
shuup.utils.patterns.pattern_matches(pattern, target)[source]

Verify that a target string matches the given pattern.

For pattern strings, compiled patterns are cached.

Parameters:
  • pattern (str|Pattern) – The pattern. Either a pattern string or a Pattern instance
  • target (str) – Target string to test against.
Returns:

Whether the test succeeded.

Return type:

bool

shuup.utils.pdf module

shuup.utils.pdf.render_html_to_pdf(html, stylesheet_paths=[])[source]
shuup.utils.pdf.html_to_pdf(html, stylesheet_paths=[])[source]
shuup.utils.pdf.wrap_pdf_in_response(pdf_data)[source]

shuup.utils.properties module

class shuup.utils.properties.MoneyProperty(value, currency)[source]

Bases: object

Property for a Money amount.

Will return Money objects when the property is being get and accepts Money objects on set. Value and currency are read/written from/to other fields.

Fields are given as locators, that is a string in dotted format, e.g. locator "foo.bar" points to instance.foo.bar where instance is an instance of the class owning the MoneyProperty.

Setting value of this property to a Money object with different currency that is currently set (in the field pointed by the currency locator), will raise an UnitMixupError.

Initialize MoneyProperty with given field locators.

Parameters:
  • value (str) – Locator for value of the Money.
  • currency (str) – Locator for currency of the Money.
value_class

alias of Money

class shuup.utils.properties.PriceProperty(value, currency, includes_tax, **kwargs)[source]

Bases: shuup.utils.properties.MoneyProperty

Property for Price object.

Similar to MoneyProperty, but also has includes_tax field.

Operaters with TaxfulPrice and TaxlessPrice objects.

Initialize PriceProperty with given field locators.

Parameters:
  • value (str) – Locator for value of the Price.
  • currency (str) – Locator for currency of the Price.
  • includes_tax (str) – Locator for includes_tax of the Price.
value_class

alias of Price

class shuup.utils.properties.TaxfulPriceProperty(value, currency)[source]

Bases: shuup.utils.properties.MoneyProperty

Initialize MoneyProperty with given field locators.

Parameters:
  • value (str) – Locator for value of the Money.
  • currency (str) – Locator for currency of the Money.
value_class

alias of TaxfulPrice

class shuup.utils.properties.TaxlessPriceProperty(value, currency)[source]

Bases: shuup.utils.properties.MoneyProperty

Initialize MoneyProperty with given field locators.

Parameters:
  • value (str) – Locator for value of the Money.
  • currency (str) – Locator for currency of the Money.
value_class

alias of TaxlessPrice

class shuup.utils.properties.MoneyPropped(*args, **kwargs)[source]

Bases: object

Mixin for transforming MoneyProperty init parameters.

Add this mixin as (first) base for the class that has MoneyProperty properties and this will make its __init__ transform passed kwargs to the fields specified in the MoneyProperty.

shuup.utils.properties.resolve(obj, path)[source]

Resolve a locator path starting from object obj.

shuup.utils.serialization module

class shuup.utils.serialization.ExtendedJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: django.core.serializers.json.DjangoJSONEncoder

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(o)[source]

shuup.utils.settings_doc module

shuup.utils.settings_doc.get_known_settings_documentation(order_by='app', only_changed=False)[source]
shuup.utils.settings_doc.get_known_settings_with_comments()[source]

shuup.utils.setup module

class shuup.utils.setup.Setup(load_from=None)[source]

Bases: object

is_valid_key(key)[source]
commit(source)[source]
values()[source]
get(key, default=None)[source]
getlist(key, default=())[source]
classmethod configure(configure)[source]

shuup.utils.text module

shuup.utils.text.flatten(str, whitespace='-')[source]

Flatten the given text into lowercase ASCII, removing diacriticals etc. Replace runs of whitespace with the given whitespace replacement.

>>> print(flatten("hellö, wörld"))
hello,-world
Parameters:
  • str (str) – The string to massage
  • whitespace (str) – The string to replace whitespace with
Returns:

A flattened string

Return type:

str

shuup.utils.text.identifierify(value, sep='_')[source]

Identifierify the given text (keep only alphanumerics and the given separator(s).

Parameters:
  • value (str) – The text to identifierify
  • sep (str) – The separator(s) to keep
Returns:

An identifierified string

Return type:

str

shuup.utils.text.snake_case(value)[source]

Snake_case the given value (join words with underscores). No other treatment is done; use identifierify for that.

shuup.utils.text.kebab_case(value)[source]

Kebab-case the given value (join words with dashes). No other treatment is done; use identifierify for that.

shuup.utils.text.camel_case(value)[source]

CamelCase the given value (join capitalized words). No other treatment is done; use identifierify for that.

shuup.utils.text.space_case(value)[source]

Space case the given value (join words that may have been otherwise separated with spaces). No other treatment is done; use identifierify for that.

shuup.utils.translation module

shuup.utils.translation.cache_translations(objects, languages=None, meta=None)[source]

Cache translation objects in given languages to the objects in one fell swoop. This will iterate a queryset, if one is passed!

Parameters:
  • objects – List or queryset of Translatable models
  • languages – Iterable of languages to fetch. In addition, all “_current_language”s will be fetched
Returns:

objects

shuup.utils.translation.cache_translations_for_tree(root_objects, languages=None)[source]

Cache translation objects in given languages, iterating MPTT trees.

Parameters:
  • root_objects (Iterable[model]) – List of MPTT models
  • languages (Iterable[str]) – List of languages

Module contents

shuup.utils.update_module_attributes(object_names, module_name)[source]

Update __module__ attribute of objects in module.

Set the __module__ attribute of the objects (resolved by the given object names from the given module name) to module_name.

Use case for this function in Shuup is to hide the actual location of objects imported from private submodules, so that they will show up nicely in the Sphinx generated API documentation. This is done by appending following line to the end of the __init__.py of the main package:

update_module_attributes(__all__, __name__)
Parameters:
  • object_names (Iterable[str]) – Names of the objects to update.
  • module_name (str) – Name of the module where the objects reside and also the new value which will be assigned to __module__ attribute of each object.
class shuup.utils.ShuupUtilsAppConfig(*args, **kwargs)[source]

Bases: shuup.apps.AppConfig

name = 'shuup.utils'
verbose_name = 'Shuup Utilities'
label = 'shuup_utils'