shoop.utils package¶
Submodules¶
shoop.utils.analog module¶
-
class
shoop.utils.analog.
LogEntryKind
[source]¶ Bases:
enumfields.enums.Enum
An enumeration.
-
OTHER
= <LogEntryKind.OTHER: 0>¶
-
AUDIT
= <LogEntryKind.AUDIT: 1>¶
-
EDIT
= <LogEntryKind.EDIT: 2>¶
-
DELETION
= <LogEntryKind.DELETION: 3>¶
-
NOTE
= <LogEntryKind.NOTE: 4>¶
-
EMAIL
= <LogEntryKind.EMAIL: 5>¶
-
WARNING
= <LogEntryKind.WARNING: 6>¶
-
ERROR
= <LogEntryKind.ERROR: 7>¶
-
-
class
shoop.utils.analog.
BaseLogEntry
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
-
target
= None¶
-
user
¶
-
kind
¶ A placeholder class that provides a way to set the attribute on the model.
-
extra
¶ A placeholder class that provides a way to set the attribute on the model.
-
BaseLogEntry.
get_kind_display
(*moreargs, **morekwargs)¶
-
BaseLogEntry.
get_next_by_created_on
(*moreargs, **morekwargs)¶
-
BaseLogEntry.
get_previous_by_created_on
(*moreargs, **morekwargs)¶
-
shoop.utils.dates module¶
-
shoop.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 ilk. Returns: Date Return type: datetime.date Raises: ValueError –
-
shoop.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 ilk. Returns: Time Return type: datetime.time Raises: ValueError –
-
shoop.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 ilk. Returns: Date Return type: datetime.date
-
shoop.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 ilk. Returns: Time Return type: datetime.time
shoop.utils.excs module¶
-
exception
shoop.utils.excs.
Problem
(message, title=None)[source]¶ Bases:
Exception
User-visible exception
-
message
¶
-
-
shoop.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]
shoop.utils.fields module¶
shoop.utils.filer module¶
-
shoop.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
-
shoop.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
-
shoop.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
-
shoop.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
shoop.utils.form_group module¶
-
exception
shoop.utils.form_group.
FormInstantiationAttributeError
[source]¶ Bases:
Exception
AttributeErrors occurring within the
forms
property are transmogrified into these.
-
class
shoop.utils.form_group.
FormDef
(name, form_class, required=True, kwargs=None)[source]¶ Bases:
object
shoop.utils.forms module¶
shoop.utils.http module¶
shoop.utils.i18n module¶
-
shoop.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
-
shoop.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
-
shoop.utils.i18n.
get_locally_formatted_datetime
(datetime)[source]¶ Return a formatted, localized version of datetime based on the current context.
-
shoop.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:
-
shoop.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
shoop.utils.importing module¶
shoop.utils.iterables module¶
-
shoop.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:
-
shoop.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]]
shoop.utils.models module¶
shoop.utils.money module¶
-
class
shoop.utils.money.
Money
[source]¶ Bases:
shoop.utils.numbers.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.
shoop.utils.multilanguage_model_form module¶
shoop.utils.numbers module¶
-
shoop.utils.numbers.
strip_non_float_chars
(s)[source]¶ Strips characters that aren’t part of normal floats.
-
shoop.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.
Parameters: s (str) – Input value Returns: Decimal Return type: Decimal
-
shoop.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
shoop.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
andTaxlessPrice
are subclasses ofUnittedDecimal
.-
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: UnittedDecimal
-
value
¶ Value of this decimal without the unit.
Return type: decimal.Decimal
-
-
exception
shoop.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
shoop.utils.objects module¶
-
shoop.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
-
shoop.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
.Parameters: Return type: Returns: True or False
-
shoop.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.Parameters: Returns: Flattened iterable
Return type: list|dict
shoop.utils.patterns module¶
-
class
shoop.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.
-
shoop.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:
shoop.utils.properties module¶
-
class
shoop.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: -
value_class
¶ alias of
Money
-
-
class
shoop.utils.properties.
PriceProperty
(value, currency, includes_tax, **kwargs)[source]¶ Bases:
shoop.utils.properties.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: -
value_class
¶ alias of
Price
-
-
class
shoop.utils.properties.
TaxfulPriceProperty
(value, currency)[source]¶ Bases:
shoop.utils.properties.MoneyProperty
Initialize MoneyProperty with given field locators.
Parameters: -
value_class
¶ alias of
TaxfulPrice
-
-
class
shoop.utils.properties.
TaxlessPriceProperty
(value, currency)[source]¶ Bases:
shoop.utils.properties.MoneyProperty
Initialize MoneyProperty with given field locators.
Parameters: -
value_class
¶ alias of
TaxlessPrice
-
-
class
shoop.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
.
shoop.utils.serialization module¶
-
class
shoop.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
.
shoop.utils.settings_doc module¶
shoop.utils.setup module¶
shoop.utils.text module¶
-
shoop.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: Returns: A flattened string
Return type:
-
shoop.utils.text.
identifierify
(value, sep='_')[source]¶ Identifierify the given text (keep only alphanumerics and the given separator(s).
Parameters: Returns: An identifierified string
Return type:
-
shoop.utils.text.
snake_case
(value)[source]¶ Snake_case the given value (join words with underscores). No other treatment is done; use
identifierify
for that.
-
shoop.utils.text.
kebab_case
(value)[source]¶ Kebab-case the given value (join words with dashes). No other treatment is done; use
identifierify
for that.
-
shoop.utils.text.
camel_case
(value)[source]¶ CamelCase the given value (join capitalized words). No other treatment is done; use
identifierify
for that.
-
shoop.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.
shoop.utils.translation module¶
-
shoop.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¶
-
shoop.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 Shoop 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.