shuup.utils package
Submodules
shuup.utils.analog module
- class shuup.utils.analog.LogEntryKind(value)[source]
Bases:
Enum
- 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:
Model
- 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 aForwardManyToOneDescriptor
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
- extra
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
- 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
shuup.utils.babel_precision_provider module
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:
- Raises:
- 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:
- Raises:
- 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:
- 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:
shuup.utils.decorators module
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.djangoenv module
- shuup.utils.djangoenv.has_installed(app)[source]
Returns whether the
app
is installed in Django, it means, it is inINSTALLED_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.
- property message
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, blank=False, **kwargs)[source]
Bases:
ModelChoiceField
shuup.utils.filer module
- 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:
Form
- base_fields = {'file': <django.forms.fields.FileField object>}
- declared_fields = {'file': <django.forms.fields.FileField object>}
- property media
Return all media required to render the widgets on this form.
- 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:
Form
- base_fields = {'file': <django.forms.fields.ImageField object>}
- declared_fields = {'file': <django.forms.fields.ImageField object>}
- property media
Return all media required to render the widgets on this form.
- 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 thesha1
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.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
shuup.utils.forms module
shuup.utils.http module
shuup.utils.i18n module
- shuup.utils.i18n.get_babel_locale(locale_string)[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.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.
- shuup.utils.i18n.get_language_name(language_code)[source]
Get a language’s name in the currently active locale.
- shuup.utils.i18n.javascript_catalog_all(request, domain='djangojs')[source]
Get JavaScript message catalog for all apps in
INSTALLED_APPS
.
- 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.importing module
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.
shuup.utils.migrations module
shuup.utils.models module
shuup.utils.money module
- class shuup.utils.money.Money(value='0', currency=None, *args, **kwargs)[source]
Bases:
UnittedDecimal
Money value with currency.
The pure decimal value is available from the base classes
value
property (preferred way) or by casting toDecimal
.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 namedcurrency
, 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.
- new(value)[source]
Create new instance with given value using same unit as self.
Post-condition: If
x = y.new(v)
, thenx.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:
- 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 ofself.currency
as returned by the precision provider, seeset_precision_provider
.
- 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 returnDecimal('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
- class shuup.utils.multilanguage_model_form.MultiLanguageModelForm(**kwargs)[source]
Bases:
TranslatableModelForm
- base_fields = {}
- clean()[source]
Avoid partially translated languages where the translated fields that are required are not set.
- save(commit=True)[source]
Save this form’s self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance.
- declared_fields = {}
- property media
Return all media required to render the widgets on this form.
shuup.utils.numbers module
- class shuup.utils.numbers.UnittedDecimal(value='0', context=None)
Bases:
Decimal
Decimal with unit.
Allows creating decimal classes that cannot be mixed, e.g. to prevent operations like:
TaxfulPrice(1) + TaxlessPrice(2)
where
TaxfulPrice
andTaxlessPrice
are subclasses ofUnittedDecimal
.- copy_negate(*args, **kwargs)[source]
Return the negation of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.
- new(value)[source]
Create new instance with given value using same unit as self.
Post-condition: If
x = y.new(v)
, thenx.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:
- quantize(exp, *args, **kwargs)[source]
Return a value equal to the first operand after rounding and having the exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000')) Decimal('1.414')
Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.
Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the first, then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given, the rounding mode of the current thread’s context is used.
- property value
Value of this decimal without the unit.
- Return type:
- 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
andobj2
. Former is instance ofUnittedDecimal
or its subclass and the other could be any object.- Variables:
obj1 (UnittedDecimal) – Involved object 1.
obj2 (Any) – Involved object 2.
- 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')
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 incomparee
.This differs from a raw == in that keys that do not exist in
source
may exist incomparee
.
- 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 ifnone_only
is set, will usevalue is None
.By default, iterables within the iterable are also compacted. This can be controlled by the
deep
argument.
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 anythingtext
– matched directlymin-max
– inclusive range matched lexicographically OR as integers if possiblewild*
– 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.
- __init__(pattern_text)[source]
Compile a pattern from the given
pattern_text
.Patterns are comma-separated atoms of the forms:
*
– matches anythingtext
– matched directlymin-max
– inclusive range matched lexicographically OR as integers if possiblewild*
– 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.
shuup.utils.pdf module
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 acceptsMoney
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 toinstance.foo.bar
whereinstance
is an instance of the class owning theMoneyProperty
.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 anUnitMixupError
.Initialize MoneyProperty with given field locators.
- Parameters:
- class shuup.utils.properties.PriceProperty(value, currency, includes_tax, **kwargs)[source]
Bases:
MoneyProperty
Property for Price object.
Similar to
MoneyProperty
, but also hasincludes_tax
field.Operaters with
TaxfulPrice
andTaxlessPrice
objects.Initialize PriceProperty with given field locators.
- Parameters:
- class shuup.utils.properties.TaxfulPriceProperty(value, currency)[source]
Bases:
MoneyProperty
Initialize MoneyProperty with given field locators.
- Parameters:
- value_class
alias of
TaxfulPrice
- class shuup.utils.properties.TaxlessPriceProperty(value, currency)[source]
Bases:
MoneyProperty
Initialize MoneyProperty with given field locators.
- Parameters:
- 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 theMoneyProperty
.
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:
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 RecursionError). 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]
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return super().default(o)
shuup.utils.settings_doc module
shuup.utils.setup module
shuup.utils.text module
- 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.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
- shuup.utils.text.identifierify(value, sep='_')[source]
Identifierify the given text (keep only alphanumerics and the given separator(s).
- 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.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.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
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) tomodule_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__)