core.bones

Submodules

Package Contents

Classes

BaseBone

The BaseBone class serves as the base class for all bone types in the ViUR framework.

Compute

ComputeInterval

ComputeMethod

Generic enumeration.

MultipleConstraints

The MultipleConstraints class is used to define constraints on multiple bones, such as the minimum

ReadFromClientError

The ReadFromClientError class represents an error that occurs while reading data from the client.

ReadFromClientErrorSeverity

ReadFromClientErrorSeverity is an enumeration that represents the severity levels of errors

UniqueLockMethod

UniqueLockMethod is an enumeration that represents different locking methods for unique constraints

UniqueValue

The UniqueValue class represents a unique constraint on a bone, ensuring that it must have a

BooleanBone

Represents a boolean data type, which can have two possible values: True or False.

CaptchaBone

The CaptchaBone is used to ensure that a user is not a bot.

ColorBone

ColorBone is a custom bone class for storing color values in the ViUR framework.

CredentialBone

A bone for storing credentials. This bone is designed to store sensitive information like

DateBone

DateBone is a bone that can handle date and/or time information. It can store date and time information

EmailBone

The EmailBone class is a designed to store syntactically validated email addresses.

FileBone

A FileBone is a custom bone class that inherits from the TreeLeafBone class, and is used to store and manage

JsonBone

This bone saves its content as a JSON-string, but unpacks its content to a dict or list when used.

KeyBone

The KeyBone is used for managing keys in the database. It provides various methods for validating,

NumericBone

A bone for storing numeric values, either integers or floats.

PasswordBone

A specialized subclass of the StringBone class designed to handle password data.

RandomSliceBone

This class is particularly useful when you want to retrieve a random sample of elements from a

RawBone

Stores its data without applying any pre/post-processing or filtering. Can be used to store

RecordBone

The RecordBone class is a specialized bone type used to store structured data. It inherits from

RelationalBone

The base class for all relational bones in the ViUR framework.

RelationalConsistency

An enumeration representing the different consistency strategies for handling stale relations in

RelationalUpdateLevel

An enumeration representing the different update levels for the RelationalBone class.

SelectCountryBone

A bone representing a country selection input field in a web application or form.

SelectBone

A SelectBone is a bone which can take a value from a certain list of values.

SortIndexBone

The SortIndexBone class is specifically designed to handle sorting indexes for data elements, which are

SpatialBone

The "SpatialBone" is a specific type of data structure designed to handle spatial data, such as geographical

StringBone

The "StringBone" represents a data field that contains text values.

TextBone

A bone for storing and validating HTML or plain text content. Can be configured to allow

TreeLeafBone

TreeLeafBone is a subclass of RelationalBone specifically designed to represent a leaf node in a tree-like data

TreeNodeBone

TreeNodeBone is a subclass of RelationalBone specifically designed to represent an intermediate node in a tree-like

UserBone

A specialized relational bone for handling user references. Extends the functionality of

Functions

translation_key_prefix_skeleton_bonename(bones_instance)

Generate a translation key prefix based on the skeleton name

translation_key_prefix_bonename(bones_instance)

Generate a translation key prefix based on the skeleton and bone name

class core.bones.BaseBone(*, compute=None, defaultValue=None, descr='', getEmptyValueFunc=None, indexed=True, isEmptyFunc=None, languages=None, multiple=False, params=None, readOnly=None, required=False, searchable=False, unique=None, vfunc=None, visible=True)

Bases: object

The BaseBone class serves as the base class for all bone types in the ViUR framework. It defines the core functionality and properties that all bones should implement.

Parameters:
  • descr (str) – Textual, human-readable description of that bone. Will be translated.

  • defaultValue (Any) – If set, this bone will be preinitialized with this value

  • required (bool | list[str] | tuple[str]) – If True, the user must enter a valid value for this bone (the viur.core refuses to save the skeleton otherwise). If a list/tuple of languages (strings) is provided, these language must be entered.

  • multiple (bool | MultipleConstraints) – If True, multiple values can be given. (ie. n:m relations instead of n:1)

  • searchable (bool) – If True, this bone will be included in the fulltext search. Can be used without the need of also been indexed.

  • vfunc (callable) – If given, a callable validating the user-supplied value for this bone. This callable must return None if the value is valid, a String containing an meaningful error-message for the user otherwise.

  • readOnly (bool) – If True, the user is unable to change the value of this bone. If a value for this bone is given along the POST-Request during Add/Edit, this value will be ignored. Its still possible for the developer to modify this value by assigning skel.bone.value.

  • visible (bool) – If False, the value of this bone should be hidden from the user. This does not protect the value from being exposed in a template, nor from being transferred to the client (ie to the admin or as hidden-value in html-form)

  • compute (Compute) –

    If set, the bone’s value will be computed in the given method.

    Note

    The kwarg ‘multiple’ is not supported by all bones

  • getEmptyValueFunc (callable) –

  • indexed (bool) –

  • isEmptyFunc (callable) –

  • languages (None | list[str]) –

  • params (dict) –

  • unique (None | UniqueValue) –

Initializes a new Bone.

type = 'hidden'
isClonedInstance = False
skel_cls

Skeleton class to which this bone instance belongs

name

Name of this bone (attribute name in the skeletons containing this bone)

__set_name__(owner, name)
Parameters:
Return type:

None

setSystemInitialized()

Can be overridden to initialize properties that depend on the Skeleton system being initialized

isInvalid(value)

Checks if the current value of the bone in the given skeleton is invalid. Returns None if the value would be valid for this bone, an error-message otherwise.

isEmpty(value)

Check if the given single value represents the “empty” value. This usually is the empty string, 0 or False.

Warning

isEmpty takes precedence over isInvalid! The empty value is always valid - unless the bone is required. But even then the empty value will be reflected back to the client.

Warning

value might be the string/object received from the user (untrusted input!) or the value returned by get

Parameters:

value (Any) –

Return type:

bool

getDefaultValue(skeletonInstance)

Retrieves the default value for the bone.

This method is called by the framework to obtain the default value of a bone when no value is provided. Derived bone classes can overwrite this method to implement their own logic for providing a default value.

Returns:

The default value of the bone, which can be of any data type.

getEmptyValue()

Returns the value representing an empty field for this bone. This might be the empty string for str/text Bones, Zero for numeric bones etc.

Return type:

Any

__setattr__(key, value)

Custom attribute setter for the BaseBone class.

This method is used to ensure that certain bone attributes, such as ‘multiple’, are only set once during the bone’s lifetime. Derived bone classes should not need to overwrite this method unless they have additional attributes with similar constraints.

Parameters:
  • key – A string representing the attribute name.

  • value – The value to be assigned to the attribute.

Raises:

AttributeError – If a protected attribute is attempted to be modified after its initial assignment.

collectRawClientData(name, data, multiple, languages, collectSubfields)

Collects raw client data for the bone and returns it in a dictionary.

This method is called by the framework to gather raw data from the client, such as form data or data from a request. Derived bone classes should overwrite this method to implement their own logic for collecting raw data.

Parameters:
  • name – A string representing the bone’s name.

  • data – A dictionary containing the raw data from the client.

  • multiple – A boolean indicating whether the bone supports multiple values.

  • languages – An optional list of strings representing the supported languages (default: None).

  • collectSubfields – A boolean indicating whether to collect data for subfields (default: False).

Returns:

A dictionary containing the collected raw client data.

parseSubfieldsFromClient()

Determines whether the function should parse subfields submitted by the client. Set to True only when expecting a list of dictionaries to be transmitted.

Return type:

bool

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value (Any) – The single value which should be loaded.

  • skel (SkeletonInstance) – The SkeletonInstance where the value should be loaded into.

  • bone_name (str) – The bone name of this bone in the SkeletonInstance.

  • client_data (dict) – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

Return type:

tuple[Any, list[ReadFromClientError] | None]

fromClient(skel, name, data)

Reads a value from the client and stores it in the skeleton instance if it is valid for the bone.

This function reads a value from the client and processes it according to the bone’s configuration. If the value is valid for the bone, it stores the value in the skeleton instance and returns None. Otherwise, the previous value remains unchanged, and a list of ReadFromClientError objects is returned.

Parameters:
  • skel (SkeletonInstance) – A SkeletonInstance object where the values should be loaded.

  • name (str) – A string representing the bone’s name.

  • data (dict) – A dictionary containing the raw data from the client.

Returns:

None if no errors occurred, otherwise a list of ReadFromClientError objects.

Return type:

None | list[ReadFromClientError]

validateMultipleConstraints(skel, name)

Validates the value of a bone against its multiple constraints and returns a list of ReadFromClientError objects for each violation, such as too many items or duplicates.

Parameters:
  • skel (SkeletonInstance) – A SkeletonInstance object where the values should be validated.

  • name (str) – A string representing the bone’s name.

Returns:

A list of ReadFromClientError objects for each constraint violation.

Return type:

list[ReadFromClientError]

singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value of the bone for storage in the database.

Derived bone classes should overwrite this method to implement their own logic for serializing single values. The serialized value should be suitable for storage in the database.

Parameters:
serialize(skel, name, parentIndexed)

Serializes this bone into a format that can be written into the datastore.

Parameters:
  • skel (SkeletonInstance) – A SkeletonInstance object containing the values to be serialized.

  • name (str) – A string representing the property name of the bone in its Skeleton (not the description).

  • parentIndexed (bool) – A boolean indicating whether the parent bone is indexed.

Returns:

A boolean indicating whether the serialization was successful.

Return type:

bool

singleValueUnserialize(val)

Unserializes a single value of the bone from the stored database value.

Derived bone classes should overwrite this method to implement their own logic for unserializing single values. The unserialized value should be suitable for use in the application logic.

unserialize(skel, name)

Deserialize bone data from the datastore and populate the bone with the deserialized values.

This function is the inverse of the serialize function. It converts data from the datastore into a format that can be used by the bones in the skeleton.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – A SkeletonInstance object containing the values to be deserialized.

  • name (str) – The property name of the bone in its Skeleton (not the description).

Returns:

True if deserialization is successful, False otherwise.

Return type:

bool

delete(skel, name)

Like postDeletedHandler, but runs inside the transaction

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • name (str) –

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Parses the searchfilter a client specified in his Request into something understood by the datastore. This function must:

    • Ignore all filters not targeting this bone

    • Safely handle malformed data in rawFilter (this parameter is directly controlled by the client)

Parameters:
  • name (str) – The property-name this bone has in its Skeleton (not the description!)

  • skel (viur.core.skeleton.SkeletonInstance) – The viur.core.db.Query this bone is part of

  • dbFilter (viur.core.db.Query) – The current viur.core.db.Query instance the filters should be applied to

  • rawFilter (dict) – The dictionary of filters the client wants to have applied

  • prefix (Optional[str]) –

Returns:

The modified viur.core.db.Query

Return type:

viur.core.db.Query

buildDBSort(name, skel, dbFilter, rawFilter)

Same as buildDBFilter, but this time its not about filtering the results, but by sorting them. Again: rawFilter is controlled by the client, so you must expect and safely handle malformed data!

Parameters:
  • name (str) – The property-name this bone has in its Skeleton (not the description!)

  • skel (viur.core.skeleton.SkeletonInstance) – The viur.core.skeleton.Skeleton instance this bone is part of

  • dbFilter (viur.core.db.Query) – The current viur.core.db.Query instance the filters should be applied to

  • rawFilter (dict) – The dictionary of filters the client wants to have applied

Returns:

The modified viur.core.db.Query, None if the query is unsatisfiable.

Return type:

Optional[viur.core.db.Query]

_hashValueForUniquePropertyIndex(value)

Generates a hash of the given value for creating unique property indexes.

This method is called by the framework to create a consistent hash representation of a value for constructing unique property indexes. Derived bone classes should overwrite this method to implement their own logic for hashing values.

Parameters:

value (str | int) – The value to be hashed, which can be a string, integer, or a float.

Returns:

A list containing a string representation of the hashed value. If the bone is multiple, the list may contain more than one hashed value.

Return type:

list[str]

getUniquePropertyIndexValues(skel, name)

Returns a list of hashes for the current value(s) of a bone in the skeleton, used for storing in the unique property value index.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – A SkeletonInstance object representing the current skeleton.

  • name (str) – The property-name of the bone in the skeleton for which the unique property index values are required (not the description!).

Returns:

A list of strings representing the hashed values for the current bone value(s) in the skeleton. If the bone has no value, an empty list is returned.

Return type:

list[str]

getReferencedBlobs(skel, name)

Returns a set of blob keys referenced from this bone

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • name (str) –

Return type:

set[str]

performMagic(valuesCache, name, isAdd)

This function applies “magically” functionality which f.e. inserts the current Date or the current user. :param isAdd: Signals wherever this is an add or edit operation.

Parameters:
  • valuesCache (dict) –

  • name (str) –

  • isAdd (bool) –

postSavedHandler(skel, boneName, key)

Can be overridden to perform further actions after the main entity has been written.

Parameters:
  • boneName (str) – Name of this bone

  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton this bone belongs to

  • key (str) – The (new?) Database Key we’ve written to

postDeletedHandler(skel, boneName, key)

Can be overridden to perform further actions after the main entity has been deleted.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton this bone belongs to

  • boneName (str) – Name of this bone

  • key (str) – The old Database Key of the entity we’ve deleted

refresh(skel, boneName)

Refresh all values we might have cached from other entities.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • boneName (str) –

Return type:

None

mergeFrom(valuesCache, boneName, otherSkel)

Merges the values from another skeleton instance into the current instance, given that the bone types match.

Parameters:
  • valuesCache (dict) – A dictionary containing the cached values for each bone in the skeleton.

  • boneName (str) – The property-name of the bone in the skeleton whose values are to be merged.

  • otherSkel (viur.core.skeleton.SkeletonInstance) – A SkeletonInstance object representing the other skeleton from which the values are to be merged.

This function clones the values from the specified bone in the other skeleton instance into the current instance, provided that the bone types match. If the bone types do not match, a warning is logged, and the merge is ignored. If the bone in the other skeleton has no value, the function returns without performing any merge operation.

setBoneValue(skel, boneName, value, append, language=None)

Sets the value of a bone in a skeleton instance, with optional support for appending and language-specific values. Sanity checks are being performed.

Parameters:
  • skel (SkeletonInstance) – The SkeletonInstance object representing the skeleton to which the bone belongs.

  • boneName (str) – The property-name of the bone in the skeleton whose value should be set or modified.

  • value (Any) – The value to be assigned. Its type depends on the type of the bone.

  • append (bool) – If True, the given value is appended to the bone’s values instead of replacing it. Only supported for bones with multiple=True.

  • language (None | str) – The language code for which the value should be set or appended, if the bone supports languages.

Returns:

A boolean indicating whether the operation was successful or not.

Return type:

bool

This function sets or modifies the value of a bone in a skeleton instance, performing sanity checks to ensure the value is valid. If the value is invalid, no modification occurs. The function supports appending values to bones with multiple=True and setting or appending language-specific values for bones that support languages.

getSearchTags(skel, name)

Returns a set of strings as search index for this bone.

This function extracts a set of search tags from the given bone’s value in the skeleton instance. The resulting set can be used for indexing or searching purposes.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton instance where the values should be loaded from. This is an instance of a class derived from viur.core.skeleton.SkeletonInstance.

  • name (str) – The name of the bone, which is a string representing the key for the bone in the skeleton. This should correspond to an existing bone in the skeleton instance.

Returns:

A set of strings, extracted from the bone value. If the bone value doesn’t have any searchable content, an empty set is returned.

Return type:

set[str]

iter_bone_value(skel, name)

Yield all values from the Skeleton related to this bone instance.

This method handles multiple/languages cases, which could save a lot of if/elifs. It always yields a triplet: index, language, value. Where index is the index (int) of a value inside a multiple bone, language is the language (str) of a multi-language-bone, and value is the value inside this container. index or language is None if the bone is single or not multi-lang.

This function can be used to conveniently iterate through all the values of a specific bone in a skeleton instance, taking into account multiple and multi-language bones.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton instance where the values should be loaded from. This is an instance of a class derived from viur.core.skeleton.SkeletonInstance.

  • name (str) – The name of the bone, which is a string representing the key for the bone in the skeleton. This should correspond to an existing bone in the skeleton instance.

Returns:

A generator which yields triplets (index, language, value), where index is the index of a value inside a multiple bone, language is the language of a multi-language bone, and value is the value inside this container. index or language is None if the bone is single or not multi-lang.

Return type:

Iterator[tuple[Optional[int], Optional[str], Any]]

_compute(skel, bone_name)

Performs the evaluation of a bone configured as compute

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • bone_name (str) –

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.Compute
fn: callable
interval: ComputeInterval
raw: bool = True
class core.bones.ComputeInterval
method: ComputeMethod
lifetime: datetime.timedelta
class core.bones.ComputeMethod

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

Always = 0
Lifetime = 1
Once = 2
OnWrite = 3
class core.bones.MultipleConstraints

The MultipleConstraints class is used to define constraints on multiple bones, such as the minimum and maximum number of entries allowed and whether duplicate values are allowed.

minAmount: int = 0

An integer representing the lower bound of how many entries can be submitted (default: 0).

maxAmount: int = 0

An integer representing the upper bound of how many entries can be submitted (default: 0).

preventDuplicates: bool = False

A boolean value indicating if the same value can be used twice (default: False).

class core.bones.ReadFromClientError

The ReadFromClientError class represents an error that occurs while reading data from the client. This class is used to store information about the error, including its severity, an error message, the field path where the error occurred, and a list of invalidated fields.

severity: ReadFromClientErrorSeverity

A ReadFromClientErrorSeverity enumeration value representing the severity of the error.

errorMessage: str

A string containing a human-readable error message describing the issue.

fieldPath: list[str]

A list of strings representing the path to the field where the error occurred.

invalidatedFields: list[str]

A list of strings containing the names of invalidated fields, if any.

class core.bones.ReadFromClientErrorSeverity

Bases: enum.Enum

ReadFromClientErrorSeverity is an enumeration that represents the severity levels of errors that can occur while reading data from the client.

NotSet = 0

No error occurred

InvalidatesOther = 1

The data is valid, for this bone, but in relation to other invalid

Empty = 2

The data is empty, but the bone requires a value

Invalid = 3

The data is invalid, but the bone requires a value

class core.bones.UniqueLockMethod

Bases: enum.Enum

UniqueLockMethod is an enumeration that represents different locking methods for unique constraints on bones. This is used to specify how the uniqueness of a value or a set of values should be enforced.

SameValue = 1

Lock this value so that there is only one entry, or lock each value individually if the bone is multiple.

SameSet = 2

Lock the same set of entries (including duplicates) regardless of their order.

SameList = 3

Lock the same set of entries (including duplicates) in a specific order.

class core.bones.UniqueValue

The UniqueValue class represents a unique constraint on a bone, ensuring that it must have a different value for each entry. This class is used to store information about the unique constraint, such as the locking method, whether to lock empty values, and an error message to display to the user if the requested value is already taken.

method: UniqueLockMethod

A UniqueLockMethod enumeration value specifying how to handle multiple values for bones with multiple=True.

lockEmpty: bool

A boolean value indicating if empty values (“”, 0) should be locked. If False, empty values are not locked, which is needed if a field is unique but not required.

message: str

A string containing an error message displayed to the user if the requested value is already taken.

class core.bones.BooleanBone(*, defaultValue=None, **kwargs)

Bases: viur.core.bones.base.BaseBone

Represents a boolean data type, which can have two possible values: True or False. BooleanBones cannot be defined as multiple=True.

Parameters:

defaultValue (bool) – The default value of the BooleanBone instance. Defaults to False.

Raises:

ValueError – If the defaultValue is not a boolean value (True or False).

Initializes a new Bone.

type = 'bool'
singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

getEmptyValue()

Returns the empty value of the BooleanBone class, which is False.

Returns:

The empty value of the BooleanBone class (False).

Return type:

bool

isEmpty(value)

Checks if the given boolean value is empty.

Parameters:

value (Any) – The boolean value to be checked.

Returns:

True if the boolean value is empty (i.e., equal to the empty value of the BooleanBone class), False otherwise.

Return type:

bool

refresh(skel, boneName)

Inverse of serialize. Evaluates whats read from the datastore and populates this bone accordingly.

Parameters:
  • name – The property-name this bone has in its Skeleton (not the description!)

  • skel (viur.core.skeleton.SkeletonInstance) –

  • boneName (str) –

Return type:

None

setBoneValue(skel, boneName, value, append, language=None)

Sets the value of the bone to the provided ‘value’. Sanity checks are performed; if the value is invalid, the bone value will revert to its original (default) value and the function will return False.

Parameters:
  • skel (SkeletonInstance) – Dictionary with the current values from the skeleton the bone belongs to

  • boneName (str) – The name of the bone that should be modified

  • value (Any) – The value that should be assigned. Its type depends on the type of the bone

  • append (bool) – If True, the given value will be appended to the existing bone values instead of replacing them. Only supported on bones with multiple=True

  • language (None | str) – Optional, the language of the value if the bone is language-aware

Returns:

A boolean indicating whether the operation succeeded or not

Return type:

bool

singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value of the bone for storage in the database.

Derived bone classes should overwrite this method to implement their own logic for serializing single values. The serialized value should be suitable for storage in the database.

Parameters:
buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Builds a database filter based on the boolean value.

Parameters:
  • name (str) – The name of the BooleanBone instance.

  • skel (viur.core.skeleton.SkeletonInstance) – The SkeletonInstance object representing the data of the current entity.

  • dbFilter (viur.core.db.Query) – The Query object representing the current database filter.

  • rawFilter (dict) – The dictionary representing the raw filter data received from the client.

  • prefix (Optional[str]) – A prefix to be added to the property name in the database filter.

Returns:

The updated Query object representing the updated database filter.

Return type:

google.cloud.ndb.query.Query

class core.bones.CaptchaBone(*, publicKey=None, privateKey=None, **kwargs)

Bases: viur.core.bones.base.BaseBone

The CaptchaBone is used to ensure that a user is not a bot.

The Captcha bone uses the Google reCAPTCHA API to perform the Captcha validation and is derived from the BaseBone.

Parameters:
  • publicKey – The public key for the Captcha validation.

  • privateKey – The private key for the Captcha validation.

  • **kwargs – Additional arguments to pass to the base class constructor.

Initializes a new Bone.

type = 'captcha'
serialize(skel, name, parentIndexed)

Serializing the Captcha bone is not possible so it return False

Parameters:
Return type:

bool

unserialize(skel, name)

Unserialize the Captcha bone.

Parameters:
  • skel – The SkeletonInstance containing the Captcha bone.

  • name – The name of the Captcha bone.

Returns:

boolean, that is true, as the Captcha bone is always unserialized successfully.

Return type:

bool

fromClient(skel, name, data)

Reads a value from the client. If this value is valid for this bone, store this value and return None. Otherwise our previous value is left unchanged and an error-message is returned.

Parameters:
  • name (str) – Our name in the skeleton

  • data (dict) – User-supplied request-data

  • skel (SkeletonInstance) –

Returns:

None or a list of errors

Return type:

None | list[viur.core.bones.base.ReadFromClientError]

class core.bones.ColorBone(*, mode='rgb', **kwargs)

Bases: viur.core.bones.base.BaseBone

ColorBone is a custom bone class for storing color values in the ViUR framework. It inherits from the BaseBone class in the viur.core.bones.base module.

Parameters:
  • type – A string representing the bone type, set to “color”.

  • mode – A string specifying the color mode, either “rgb” or “rgba”. Default is “rgb”.

  • **kwargs – Additional keyword arguments passed to the BaseBone constructor.

Initializes a new Bone.

type = 'color'
singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

class core.bones.CredentialBone(*, max_length=None, **kwargs)

Bases: viur.core.bones.string.StringBone

A bone for storing credentials. This bone is designed to store sensitive information like passwords, API keys, or other secret strings. This is always empty if read from the database. If it’s saved, its ignored if its values is still empty. If its value is not empty, it will update the value in the database

Variables:

type (str) – The type identifier of the bone, set to “str.credential”.

Parameters:

max_length (int) –

Initializes a new StringBone.

Parameters:
  • caseSensitive – When filtering for values in this bone, should it be case-sensitive?

  • max_length (int) – The maximum length allowed for values of this bone. Set to None for no limitation.

  • min_length – The minimum length allowed for values of this bone. Set to None for no limitation.

  • natural_sorting – Allows a more natural sorting than the default sorting on the plain values. This uses the .sort_idx property. True enables sorting according to DIN 5007 Variant 2. With passing a callable, a custom transformer method can be set that creates the value for the index property.

  • kwargs – Inherited arguments from the BaseBone.

type = 'str.credential'
isInvalid(value)

Returns None if the value would be valid for this bone, an error-message otherwise.

serialize(skel, name, parentIndexed)

Serializes the bone’s value for the database.

Updates the value in the entity only if a new value is supplied. Ensures the value is never indexed.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance that the bone is part of.

  • name (str) – The name of the bone attribute.

  • parentIndexed (bool) – Indicates whether the parent entity is indexed.

Returns:

True if the value was updated in the database, False otherwise.

Return type:

bool

unserialize(valuesCache, name)

Unserializes the bone’s value from the database.

This method always returns an empty dictionary as the CredentialBone’s value is always empty when read from the database.

Parameters:
  • valuesCache (dict) – A dictionary containing the serialized values from the datastore.

  • name (str) – The name of the bone attribute.

Returns:

An empty dictionary, as the CredentialBone’s value is always empty when read from the database.

Return type:

dict

singleValueFromClient(value, skel, bone_name, client_data)

Returns None and the escaped value if the value would be valid for this bone, otherwise the empty value and an error-message.

class core.bones.DateBone(*, creationMagic=False, date=True, localize=None, naive=False, time=True, updateMagic=False, **kwargs)

Bases: viur.core.bones.base.BaseBone

DateBone is a bone that can handle date and/or time information. It can store date and time information separately, as well as localize the time based on the user’s timezone.

Parameters:
  • creationMagic (bool) – Use the current time as value when creating an entity; ignoring this bone if the entity gets updated.

  • updateMagic (bool) – Use the current time whenever this entity is saved.

  • date (bool) – If True, the bone will contain date information.

  • time (bool) – If True, the bone will contain time information.

  • localize (bool) – If True, the user’s timezone is assumed for input and output. This is only valid if both ‘date’ and ‘time’ are set to True. By default, UTC time is used.

  • naive (bool) –

Initializes a new DateBone.

Parameters:
  • creationMagic (bool) – Use the current time as value when creating an entity; ignoring this bone if the entity gets updated.

  • updateMagic (bool) – Use the current time whenever this entity is saved.

  • date (bool) – Should this bone contain a date-information?

  • time (bool) – Should this bone contain time information?

  • localize (bool) – Assume users timezone for in and output? Only valid if this bone contains date and time-information! Per default, UTC time is used.

  • naive (bool) – Use naive datetime for this bone, the default is aware.

type = 'date'
singleValueFromClient(value, skel, bone_name, client_data)

Reads a value from the client. If the value is valid for this bone, it stores the value and returns None. Otherwise, the previous value is left unchanged, and an error message is returned. The value is assumed to be in the local time zone only if both self.date and self.time are set to True and self.localize is True.

Value is valid if, when converted into String, it complies following formats:

is digit (may include one ‘-’) and valid POSIX timestamp: converted from timestamp; assumes UTC timezone is digit (may include one ‘-’) and NOT valid POSIX timestamp and not date and time: interpreted as seconds after epoch ‘now’: current time ‘nowX’, where X converted into String is added as seconds to current time ‘%H:%M:%S’ if not date and time ‘%M:%S’ if not date and time ‘%S’ if not date and time ‘%Y-%m-%d %H:%M:%S’ (ISO date format) ‘%Y-%m-%d %H:%M’ (ISO date format) ‘%Y-%m-%d’ (ISO date format) ‘%m/%d/%Y %H:%M:%S’ (US date-format) ‘%m/%d/%Y %H:%M’ (US date-format) ‘%m/%d/%Y’ (US date-format) ‘%d.%m.%Y %H:%M:%S’ (EU date-format) ‘%d.%m.%Y %H:%M’ (EU date-format) ‘%d.%m.%Y’ (EU date-format)

The resulting year must be >= 1900.

Parameters:
  • bone_name – Our name in the skeleton

  • client_dataUser-supplied request-data, has to be of valid format

Returns:

tuple[datetime or None, [Errors] or None]

isInvalid(value)

Validates the input value to ensure that the year is greater than or equal to 1900. If the year is less than 1900, it returns an error message. Otherwise, it calls the superclass’s isInvalid method to perform any additional validations.

This check is important because the strftime function, which is used to format dates in Python, will break if the year is less than 1900.

Parameters:

value (datetime) – The input value to be validated, expected to be a datetime object.

Returns:

An error message if the year is less than 1900, otherwise the result of calling the superclass’s isInvalid method.

Return type:

str or None

guessTimeZone()

Tries to guess the user’s time zone based on request headers. If the time zone cannot be guessed, it falls back to using the UTC time zone. The guessed time zone is then cached for future use during the current request.

Returns:

The guessed time zone for the user or a default time zone (UTC) if the time zone cannot be guessed.

Return type:

pytz timezone object

singleValueSerialize(value, skel, name, parentIndexed)

Prepares a single value for storage by removing any unwanted parts of the datetime object, such as microseconds or adjusting the date and time components depending on the configuration of the dateBone. The method also ensures that the datetime object is timezone aware.

Parameters:
  • value (datetime) – The input datetime value to be serialized.

  • skel (SkeletonInstance) – The instance of the skeleton that contains this bone.

  • name (str) – The name of the bone in the skeleton.

  • parentIndexed (bool) – A boolean indicating if the parent bone is indexed.

Returns:

The serialized datetime value with unwanted parts removed and timezone-aware.

Return type:

datetime

singleValueUnserialize(value)

Converts the serialized datetime value back to its original form. If the datetime object is timezone aware, it adjusts the timezone based on the configuration of the dateBone.

Parameters:

value (datetime) – The input serialized datetime value to be unserialized.

Returns:

The unserialized datetime value with the appropriate timezone applied or None if the input value is not a valid datetime object.

Return type:

datetime or None

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Constructs a datastore filter for date and/or time values based on the given raw filter. It parses the raw filter and, if successful, applies it to the datastore query.

Parameters:
  • name (str) – The name of the dateBone in the skeleton.

  • skel (SkeletonInstance) – The skeleton instance containing the dateBone.

  • dbFilter (db.Query) – The datastore query to which the filter will be applied.

  • rawFilter (Dict) – The raw filter dictionary containing the filter values.

  • prefix (Optional[str]) – An optional prefix to use for the filter key, defaults to None.

Returns:

The datastore query with the constructed filter applied.

Return type:

db.Query

performMagic(valuesCache, name, isAdd)

Automatically sets the current date and/or time for a dateBone when a new entry is created or an existing entry is updated, depending on the configuration of creationMagic and updateMagic.

Parameters:
  • valuesCache (dict) – The cache of values to be stored in the datastore.

  • name (str) – The name of the dateBone in the skeleton.

  • isAdd (bool) – A flag indicating whether the operation is adding a new entry (True) or updating an existing one (False).

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.EmailBone(*, caseSensitive=True, max_length=254, min_length=None, natural_sorting=False, **kwargs)

Bases: viur.core.bones.string.StringBone

The EmailBone class is a designed to store syntactically validated email addresses.

This class provides an email validation method, ensuring that the given email address conforms to the required format and structure.

Initializes a new StringBone.

Parameters:
  • caseSensitive (bool) – When filtering for values in this bone, should it be case-sensitive?

  • max_length (int | None) – The maximum length allowed for values of this bone. Set to None for no limitation.

  • min_length (int | None) – The minimum length allowed for values of this bone. Set to None for no limitation.

  • natural_sorting (bool | Callable) – Allows a more natural sorting than the default sorting on the plain values. This uses the .sort_idx property. True enables sorting according to DIN 5007 Variant 2. With passing a callable, a custom transformer method can be set that creates the value for the index property.

  • kwargs – Inherited arguments from the BaseBone.

type = 'str.email'

A string representing the type of the bone, in this case “str.email”.

isInvalid(value)

Checks if the provided email address is valid or not.

Parameters:

value (str) – The email address to be validated.

Returns:

An error message if the email address is invalid or None if it is valid.

Return type:

str, None

The method checks if the provided email address is valid according to the following criteria:

  1. The email address must not be empty.

  2. The email address must be shorter than 256 characters.

  3. The local part (account) must be shorter than or equal to 64 characters.

  4. The email address must contain an “@” symbol, separating the local part (account) and the domain part.

  5. The domain part must be a valid IDNA-encoded string and should not contain any spaces.

  6. The local part (account) should only contain valid characters.

  7. The local part (account) can also contain Unicode characters within the range of U+0080 to U+10FFFF.

class core.bones.FileBone(*, derive=None, maxFileSize=None, validMimeTypes=None, refKeys=('name', 'mimetype', 'size', 'width', 'height', 'derived'), **kwargs)

Bases: viur.core.bones.treeleaf.TreeLeafBone

A FileBone is a custom bone class that inherits from the TreeLeafBone class, and is used to store and manage file references in a ViUR application.

Parameters:
  • format – Hint for the UI how to display a file entry (defaults to it’s filename)

  • maxFileSize (None | int) – The maximum filesize accepted by this bone in bytes. None means no limit. This will always be checked against the original file uploaded - not any of it’s derivatives.

  • derive (None | dict[str, Any]) –

    A set of functions used to derive other files from the referenced ones. Used fe. to create thumbnails / images for srcmaps from hires uploads. If set, must be a dictionary from string (a key from conf.file_derivations) to the parameters passed to that function. The parameters can be any type (including None) that can be json-serialized.

    # Example
    derive = { "thumbnail": [{"width": 111}, {"width": 555, "height": 666}]}
    

  • validMimeTypes (None | list[str]) –

    A list of Mimetypes that can be selected in this bone (or None for any) Wildcards (“image/*”) are supported.

    # Example
    validMimeTypes=["application/pdf", "image/*"]
    

  • refKeys (Optional[Iterable[str]]) –

Initializes a new Filebone. All properties inherited by RelationalBone are supported.

Parameters:
  • format – Hint for the UI how to display a file entry (defaults to it’s filename)

  • maxFileSize (None | int) – The maximum filesize accepted by this bone in bytes. None means no limit.

  • derive (None | dict[str, Any]) –

  • validMimeTypes (None | list[str]) –

  • refKeys (Optional[Iterable[str]]) –

This will always be checked against the original file uploaded - not any of it’s derivatives. :param derive: A set of functions used to derive other files from the referenced ones. Used to create thumbnails and images for srcmaps from hires uploads. If set, must be a dictionary from string (a key from) conf.file_derivations) to the parameters passed to that function. The parameters can be any type (including None) that can be json-serialized.

# Example
derive = {"thumbnail": [{"width": 111}, {"width": 555, "height": 666}]}
Parameters:
  • validMimeTypes (None | list[str]) –

    A list of Mimetypes that can be selected in this bone (or None for any). Wildcards (‘image*’) are supported.

    #Example
    validMimeTypes=["application/pdf", "image/*"]
    

  • derive (None | dict[str, Any]) –

  • maxFileSize (None | int) –

  • refKeys (Optional[Iterable[str]]) –

kind = 'file'

The kind of this bone is ‘file’

type = 'relational.tree.leaf.file'

The type of this bone is ‘relational.tree.leaf.file’.

isInvalid(value)

Checks if the provided value is invalid for this bone based on its MIME type and file size.

Parameters:

value (dict) – The value to check for validity.

Returns:

None if the value is valid, or an error message if it is invalid.

postSavedHandler(skel, boneName, key)

Handles post-save processing for the FileBone, including ensuring derived files are built.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance this bone belongs to.

  • boneName (str) – The name of the bone.

  • key (db.Key) – The datastore key of the skeleton.

This method first calls the postSavedHandler of its superclass. Then, it checks if the derive attribute is set and if there are any values in the skeleton for the given bone. If so, it handles the creation of derived files based on the provided configuration.

If the values are stored as a dictionary without a “dest” key, it assumes a multi-language setup and iterates over each language to handle the derived files. Otherwise, it handles the derived files directly.

getReferencedBlobs(skel, name)

Retrieves the referenced blobs in the FileBone.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance this bone belongs to.

  • name (str) – The name of the bone.

Returns:

A set of download keys for the referenced blobs.

Return type:

Set[str]

This method iterates over the bone values for the given skeleton and bone name. It skips values that are None. For each non-None value, it adds the download key of the referenced blob to a set. Finally, it returns the set of unique download keys for the referenced blobs.

refresh(skel, boneName)

Refreshes the FileBone by recreating file entries if needed and importing blobs from ViUR 2.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance this bone belongs to.

  • boneName (str) – The name of the bone.

This method defines an inner function, recreateFileEntryIfNeeded(val), which is responsible for recreating the weak file entry referenced by the relation in val if it doesn’t exist (e.g., if it was deleted by ViUR 2). It initializes a new skeleton for the “file” kind and checks if the file object already exists. If not, it recreates the file entry with the appropriate properties and saves it to the database.

The main part of the refresh method calls the superclass’s refresh method and checks if the configuration contains a ViUR 2 import blob source. If it does, it iterates through the file references in the bone value, imports the blobs from ViUR 2, and recreates the file entries if needed using the inner function.

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.JsonBone(*, indexed=False, multiple=False, languages=None, schema={}, **kwargs)

Bases: viur.core.bones.raw.RawBone

This bone saves its content as a JSON-string, but unpacks its content to a dict or list when used. :param schema If provided we can control and verify which data to accept.

# Example
schema= {"type": "object", "properties" :{"price": {"type": "number"},"name": {"type": "string"}}
# This will only accept the provided JSON when price is a number and name is a string.

Initializes a new Bone.

Parameters:
  • indexed (bool) –

  • multiple (bool) –

  • languages (bool) –

  • schema (Mapping) –

type = 'raw.json'
singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value of the bone for storage in the database.

Derived bone classes should overwrite this method to implement their own logic for serializing single values. The serialized value should be suitable for storage in the database.

Parameters:
singleValueUnserialize(val)

Unserializes a single value of the bone from the stored database value.

Derived bone classes should overwrite this method to implement their own logic for unserializing single values. The unserialized value should be suitable for use in the application logic.

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value (str | list | dict) – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.KeyBone(*, descr='Key', readOnly=True, visible=False, allowed_kinds=None, check=False, **kwargs)

Bases: viur.core.bones.base.BaseBone

The KeyBone is used for managing keys in the database. It provides various methods for validating, converting, and storing key values, as well as querying the database. Key management is crucial for maintaining relationships between entities in the database, and the KeyBone class helps ensure that keys are handled correctly and efficiently throughout the system.

Parameters:
  • descr (str) – The description of the KeyBone.

  • readOnly (bool) – Whether the KeyBone is read-only.

  • visible (bool) – Whether the KeyBone is visible.

  • allowed_kinds (None | list[str]) – The allowed entity kinds for the KeyBone.

  • check (bool) – Whether to check for entity existence.

  • allowed_kinds

Initializes a new Bone.

type = 'key'
singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

unserialize(skel, name)

This method is the inverse of :meth:serialize. It reads the key value from the datastore and populates the corresponding KeyBone in the Skeleton. The method converts the value from the datastore into an appropriate format for further use in the program.

Parameters:
  • skel (viur.core.skeleton.SkeletonValues) – The SkeletonValues instance this bone is a part of.

  • name (str) – The property name of this bone in the Skeleton (not the description).

Returns:

A boolean value indicating whether the operation was successful. Returns True if the key value was successfully unserialized and added to the accessedValues of the Skeleton, and False otherwise.

Return type:

bool

Note

The method contains an inner function, fixVals(val), which normalizes and validates the key values before populating the bone.

serialize(skel, name, parentIndexed)

This method serializes the KeyBone into a format that can be written to the datastore. It converts the key value from the Skeleton object into a format suitable for storage in the datastore.

Parameters:
  • skel (SkeletonInstance) – The SkeletonInstance this bone is a part of.

  • name (str) – The property name of this bone in the Skeleton (not the description).

  • parentIndexed (bool) – A boolean value indicating whether the parent entity is indexed or not.

Returns:

A boolean value indicating whether the operation was successful. Returns True if the key value was successfully serialized and added to the datastore entity, and False otherwise.

Return type:

bool

Note

Key values are always indexed, so the method discards any exclusion from indexing for key values.

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

This method parses the search filter specified by the client in their request and converts it into a format that can be understood by the datastore. It takes care of ignoring filters that do not target this bone and safely handles malformed data in the raw filter.

Parameters:
  • name (str) – The property name of this bone in the Skeleton (not the description).

  • skel (viur.core.skeleton.SkeletonInstance) – The :class:viur.core.skeleton.SkeletonInstance this bone is a part of.

  • dbFilter (viur.core.db.Query) – The current :class:viur.core.db.Query instance the filters should be applied to.

  • rawFilter (dict) – The dictionary of filters the client wants to have applied.

  • prefix (Optional[str]) – An optional string to prepend to the filter key. Defaults to None.

Returns:

The modified :class:viur.core.db.Query.

Return type:

viur.core.db.Query

The method takes the following steps:

  1. Decodes the provided key(s) from the raw filter.

  2. If the filter contains a list of keys, it iterates through the list, creating a new

    filter for each key and appending it to the list of queries.

  3. If the filter contains a single key, it applies the filter directly to the query.

  4. In case of any invalid key or other issues, it raises a RuntimeError.

class core.bones.NumericBone(*, max=MAX, min=MIN, mode=None, precision=0, **kwargs)

Bases: viur.core.bones.base.BaseBone

A bone for storing numeric values, either integers or floats. For floats, the precision can be specified in decimal-places.

Parameters:
  • precision (int) – How may decimal places should be saved. Zero casts the value to int instead of float.

  • min (int | float) – Minimum accepted value (including).

  • max (int | float) – Maximum accepted value (including).

Initializes a new NumericBone.

type = 'numeric'
__setattr__(key, value)

Sets the attribute with the specified key to the given value.

This method is overridden in the NumericBone class to handle the special case of setting the ‘multiple’ attribute to True while the bone is of type float. In this case, an AssertionError is raised to prevent creating a multiple float bone.

Parameters:
  • key – The name of the attribute to be set.

  • value – The value to set the attribute to.

Raises:

AssertionError – If the ‘multiple’ attribute is set to True for a float bone.

isInvalid(value)

This method checks if a given value is invalid (e.g., NaN) for the NumericBone instance.

Parameters:

value – The value to be checked for validity.

Returns:

Returns a string “NaN not allowed” if the value is invalid (NaN), otherwise None.

getEmptyValue()

This method returns an empty value depending on the precision attribute of the NumericBone instance.

Returns:

Returns 0 for integers (when precision is 0) or 0.0 for floating-point numbers (when precision is non-zero).

isEmpty(value)

This method checks if a given raw value is considered empty for the NumericBone instance. It attempts to convert the raw value into a valid numeric value (integer or floating-point number), depending on the precision attribute of the NumericBone instance.

Parameters:

value (Any) – The raw value to be checked for emptiness.

Returns:

Returns True if the raw value is considered empty, otherwise False.

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Parses the searchfilter a client specified in his Request into something understood by the datastore. This function must:

    • Ignore all filters not targeting this bone

    • Safely handle malformed data in rawFilter (this parameter is directly controlled by the client)

Parameters:
  • name (str) – The property-name this bone has in its Skeleton (not the description!)

  • skel (viur.core.skeleton.SkeletonInstance) – The viur.core.db.Query this bone is part of

  • dbFilter (viur.core.db.Query) – The current viur.core.db.Query instance the filters should be applied to

  • rawFilter (dict) – The dictionary of filters the client wants to have applied

  • prefix (Optional[str]) –

Returns:

The modified viur.core.db.Query

Return type:

viur.core.db.Query

getSearchTags(skel, name)

This method generates a set of search tags based on the numeric values stored in the NumericBone instance. It iterates through the bone values and adds the string representation of each value to the result set.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton instance containing the bone.

  • name (str) – The name of the bone.

Returns:

Returns a set of search tags as strings.

Return type:

set[str]

_convert_to_numeric(value)

Convert a value to an int or float considering the precision.

If the value is not convertable an exception will be raised.

Parameters:

value (Any) –

Return type:

int | float

refresh(skel, boneName)

Ensure the value is numeric or None.

This ensures numeric values, for example after changing a bone from StringBone to a NumericBone.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • boneName (str) –

Return type:

None

iter_bone_value(skel, name)

Yield all values from the Skeleton related to this bone instance.

This method handles multiple/languages cases, which could save a lot of if/elifs. It always yields a triplet: index, language, value. Where index is the index (int) of a value inside a multiple bone, language is the language (str) of a multi-language-bone, and value is the value inside this container. index or language is None if the bone is single or not multi-lang.

This function can be used to conveniently iterate through all the values of a specific bone in a skeleton instance, taking into account multiple and multi-language bones.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The skeleton instance where the values should be loaded from. This is an instance of a class derived from viur.core.skeleton.SkeletonInstance.

  • name (str) – The name of the bone, which is a string representing the key for the bone in the skeleton. This should correspond to an existing bone in the skeleton instance.

Returns:

A generator which yields triplets (index, language, value), where index is the index of a value inside a multiple bone, language is the language of a multi-language bone, and value is the value inside this container. index or language is None if the bone is single or not multi-lang.

Return type:

Iterator[tuple[Optional[int], Optional[str], Any]]

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.PasswordBone(*, descr='Password', test_threshold=4, tests=tests, **kwargs)

Bases: viur.core.bones.string.StringBone

A specialized subclass of the StringBone class designed to handle password data.

The PasswordBone hashes the password before saving it to the database and prevents it from being read directly. It also includes various tests to determine the strength of the entered password.

Initializes a new PasswordBone.

Parameters:
  • test_threshold (int) – The minimum number of tests the password must pass.

  • password_tests – Defines separate tests specified as tuples of regex, hint and required-flag.

  • descr (str) –

  • tests (Iterable[Iterable[Tuple[str, str, bool]]]) –

type = 'password'

A string representing the bone type, which is “password” in this case.

saltLength = 13
tests: Iterable[Iterable[Tuple[str, str, bool]]] = (('^.*[A-Z].*$',), ('^.*[a-z].*$',), ('^.*\\d.*$',), ('^.*\\W.*$',), ('^.{8,}$',))

Provides tests based on regular expressions to test the password strength.

Note: The provided regular expressions have to produce exactly the same results in Python and JavaScript.

This requires that some feature either cannot be used, or must be rewritten to match on both engines.

isInvalid(value)

Determines if the entered password is invalid based on the length and strength requirements. It checks if the password is empty, too short, or too weak according to the password tests specified in the class.

Parameters:

value (str) – The password to be checked.

Returns:

True if the password is invalid, otherwise False.

Return type:

bool

fromClient(skel, name, data)

Processes the password field from the client data, validates it, and stores it in the skeleton instance after hashing. This method performs several checks, such as ensuring that the password field is present in the data, that the password is not empty, and that it meets the length and strength requirements. If any of these checks fail, a ReadFromClientError is returned.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance to store the password in.

  • name (str) – The name of the password field.

  • data (dict) – The data dictionary containing the password field value.

Returns:

None if the password is valid, otherwise a list of ReadFromClientErrors.

Return type:

Union[None, List[ReadFromClientError]]

serialize(skel, name, parentIndexed)

Processes and stores the password field from the client data into the skeleton instance after hashing and validating it. This method carries out various checks, such as:

  • Ensuring that the password field is present in the data.

  • Verifying that the password is not empty.

  • Confirming that the password meets the length and strength requirements.

If any of these checks fail, a ReadFromClientError is returned.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance where the password will be stored as a hashed value along with its salt.

  • name (str) – The name of the password field used to access the password value in the data dictionary.

  • data (dict) – The data dictionary containing the password field value, typically submitted by the client.

  • parentIndexed (bool) –

Returns:

None if the password is valid and successfully stored in the skeleton instance; otherwise, a list of ReadFromClientErrors containing detailed information about the errors.

Return type:

Union[None, List[ReadFromClientError]]

unserialize(skeletonValues, name)

This method does not unserialize password values from the datastore. It always returns False, indicating that no password value will be unserialized.

Parameters:
  • skeletonValues (dict) – The dictionary containing the values from the datastore.

  • name (str) – The name of the password field.

Returns:

False, as no password value will be unserialized.

Return type:

bool

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.RandomSliceBone(*, visible=False, readOnly=True, slices=2, sliceSize=0.5, **kwargs)

Bases: viur.core.bones.base.BaseBone

This class is particularly useful when you want to retrieve a random sample of elements from a larger dataset without needing to fetch all the data from the database. By performing multiple subqueries and processing the results, RandomSliceBone provides an efficient way to get a randomized selection of elements from the database query. Simulates the orderby=random from SQL. If you sort by this bone, the query will return a random set of elements from that query.

Parameters:
  • visible – Indicates if the bone is visible, defaults to False.

  • readOnly – Indicates if the bone is read-only, defaults to True.

  • slices – The number of slices to use, defaults to 2.

  • sliceSize – The size of each slice, defaults to 0.5.

  • kwargs – Additional keyword arguments.

Initializes a new RandomSliceBone.

type = 'randomslice'
serialize(skel, name, parentIndexed)

Serializes the bone into a format that can be written into the datastore. Instead of using the existing value, it writes a randomly chosen float in the range [0, 1) as the value for this bone.

Parameters:
  • skel (SkeletonInstance) – The SkeletonInstance this bone is part of.

  • name (str) – The property name this bone has in its Skeleton (not the description).

  • parentIndexed (bool) – Indicates if the parent bone is indexed.

Returns:

Returns True if the serialization is successful.

Return type:

bool

buildDBSort(name, skel, dbFilter, rawFilter)

Modifies the database query to return a random selection of elements by creating multiple subqueries, each covering a slice of the data. This method doesn’t just change the order of the selected elements, but also changes which elements are returned.

Parameters:
  • name (str) – The property name this bone has in its Skeleton (not the description).

  • skel (SkeletonInstance) – The :class:viur.core.skeleton.Skeleton instance this bone is part of.

  • dbFilter (db.Query) – The current :class:viur.core.db.Query instance the filters should be applied to.

  • rawFilter (Dict) – The dictionary of filters the client wants to have applied.

Returns:

The modified :class:viur.core.db.Query instance.

Return type:

Optional[db.Query]

Note

The rawFilter is controlled by the client, so you must expect and safely handle malformed data.

The method also contains an inner function, applyFilterHook, that applies the filter hook to the given filter if set, or returns the unmodified filter. This allows the orderby=random functionality to be used in relational queries as well.

calculateInternalMultiQueryLimit(query, targetAmount)

Calculates the number of entries to be fetched in each subquery.

Parameters:
  • query (db.Query) – The :class:viur.core.db.Query instance.

  • targetAmount (int) – The number of entries to be returned from the db.Query.

Returns:

The number of elements the db.Query should fetch on each subquery.

Return type:

int

customMultiQueryMerge(dbFilter, result, targetAmount)

Merges the results of multiple subqueries by randomly selecting ‘targetAmount’ elements from the combined ‘result’ list.

Parameters:
  • dbFilter (db.Query) – The db.Query instance calling this function.

  • result (List[db.Entity]) – The list of results for each subquery that has been run.

  • targetAmount (int) – The number of results to be returned from the db.Query.

Returns:

A list of elements to be returned from the db.Query.

Return type:

List[db.Entity]

class core.bones.RawBone(*, compute=None, defaultValue=None, descr='', getEmptyValueFunc=None, indexed=True, isEmptyFunc=None, languages=None, multiple=False, params=None, readOnly=None, required=False, searchable=False, unique=None, vfunc=None, visible=True)

Bases: viur.core.bones.base.BaseBone

Stores its data without applying any pre/post-processing or filtering. Can be used to store non-html content. Use the dot-notation like “raw.markdown” or similar to describe subsequent types.

..Warning: Using this bone will lead to security vulnerabilities like reflected XSS unless the

data is either otherwise validated/stripped or from a trusted source! Don’t use this unless you fully understand it’s implications!

Initializes a new Bone.

Parameters:
  • compute (Compute) –

  • defaultValue (Any) –

  • descr (str) –

  • getEmptyValueFunc (callable) –

  • indexed (bool) –

  • isEmptyFunc (callable) –

  • languages (None | list[str]) –

  • multiple (bool | MultipleConstraints) –

  • params (dict) –

  • readOnly (bool) –

  • required (bool | list[str] | tuple[str]) –

  • searchable (bool) –

  • unique (None | UniqueValue) –

  • vfunc (callable) –

  • visible (bool) –

type = 'raw'
singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

class core.bones.RecordBone(*, format=None, indexed=False, using=None, **kwargs)

Bases: viur.core.bones.base.BaseBone

The RecordBone class is a specialized bone type used to store structured data. It inherits from the BaseBone class. The RecordBone class is designed to store complex data structures, such as nested dictionaries or objects, by using a related skeleton class (the using parameter) to manage the internal structure of the data.

Parameters:
  • format (str) – Optional string parameter to specify the format of the record bone.

  • indexed (bool) – Optional boolean parameter to indicate if the record bone is indexed. Defaults to False.

  • using (viur.core.skeleton.RelSkel) – A class that inherits from ‘viur.core.skeleton.RelSkel’ to be used with the RecordBone.

  • kwargs – Additional keyword arguments to be passed to the BaseBone constructor.

Initializes a new Bone.

type = 'record'
singleValueUnserialize(val)

Unserializes a single value, creating an instance of the ‘using’ class and unserializing the value into it.

Parameters:

val – The value to unserialize.

Returns:

An instance of the ‘using’ class with the unserialized data.

Raises:

AssertionError – If the unserialized value is not a dictionary.

singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value by calling the serialize method of the ‘using’ skeleton instance.

Parameters:
  • value – The value to be serialized, which should be an instance of the ‘using’ skeleton.

  • skel (SkeletonInstance) – The parent skeleton instance.

  • name (str) – The name of the bone.

  • parentIndexed (bool) – A boolean indicating if the parent bone is indexed.

Returns:

The serialized value.

parseSubfieldsFromClient()

Determines if the current request should attempt to parse subfields received from the client. This should only be set to True if a list of dictionaries is expected to be transmitted.

Return type:

bool

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

getSearchTags(skel, name)

Collects search tags from the ‘using’ skeleton instance for the given bone.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – The parent skeleton instance.

  • name (str) – The name of the bone.

Returns:

A set of search tags generated from the ‘using’ skeleton instance.

Return type:

set[str]

getSearchDocumentFields(valuesCache, name, prefix='')

Generates a list of search document fields for the given values cache, name, and optional prefix.

Parameters:
  • valuesCache (dict) – A dictionary containing the cached values.

  • name (str) – The name of the bone to process.

  • prefix (str) – An optional prefix to use for the search document fields, defaults to an empty string.

Returns:

A list of search document fields.

Return type:

list

getReferencedBlobs(skel, name)

Retrieves a set of referenced blobs for the given skeleton instance and name.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance to process.

  • name (str) – The name of the bone to process.

Returns:

A set of referenced blobs.

Return type:

set[str]

abstract getUniquePropertyIndexValues(valuesCache, name)

This method is intentionally not implemented as it’s not possible to determine how to derive a key from the related skeleton being used (i.e., which fields to include and how).

Parameters:
  • valuesCache (dict) –

  • name (str) –

Return type:

list[str]

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.RelationalBone(*, consistency=RelationalConsistency.Ignore, format='$(dest.name)', kind=None, module=None, parentKeys={'name'}, refKeys={'name'}, updateLevel=RelationalUpdateLevel.Always, using=None, **kwargs)

Bases: viur.core.bones.base.BaseBone

The base class for all relational bones in the ViUR framework. RelationalBone is used to create and manage relationships between database entities. This class provides basic functionality and attributes that can be extended by other specialized relational bone classes, such as N1Relation, N2NRelation, and Hierarchy. This implementation prioritizes read efficiency and is suitable for situations where data is read more frequently than written. However, it comes with increased write operations when writing an entity to the database. The additional write operations depend on the type of relationship: multiple=True RelationalBones or 1:N relations.

The implementation does not instantly update relational information when a skeleton is updated; instead, it triggers a deferred task to update references. This may result in outdated data until the task is completed.

Note: Filtering a list by relational properties uses the outdated data.

Example: - Entity A references Entity B. - Both have a property “name.” - Entity B is updated (its name changes). - Entity A’s RelationalBone values still show Entity B’s old name.

It is not recommended for cases where data is read less frequently than written, as there is no write-efficient method available yet.

Parameters:
  • kind (str) – KindName of the referenced property.

  • module (Optional[str]) – Name of the module which should be used to select entities of kind “type”. If not set, the value of “type” will be used (the kindName must match the moduleName)

  • refKeys (Optional[Iterable[str]]) – A list of properties to include from the referenced property. These properties will be available in the template without having to fetch the referenced property. Filtering is also only possible by properties named here!

  • parentKeys (Optional[Iterable[str]]) – A list of properties from the current skeleton to include. If mixing filtering by relational properties and properties of the class itself, these must be named here.

  • multiple – If True, allow referencing multiple Elements of the given class. (Eg. n:n-relation). Otherwise its n:1, (you can only select exactly one). It’s possible to use a unique constraint on this bone, allowing for at-most-1:1 or at-most-1:n relations. Instead of true, it’s also possible to use a `class MultipleConstraints` instead.

  • format (str) –

    Hint for the frontend how to display such an relation. This is now a python expression evaluated by safeeval on the client side. The following values will be passed to the expression:

    • value

      The value to display. This will be always a dict (= a single value) - even if the relation is multiple (in which case the expression is evaluated once per referenced entity)

    • structure

      The structure of the skeleton this bone is part of as a dictionary as it’s transferred to the fronted by the admin/vi-render.

    • language

      The current language used by the frontend in ISO2 code (eg. “de”). This will be always set, even if the project did not enable the multi-language feature.

  • updateLevel (RelationalUpdateLevel) –

    Indicates how ViUR should keep the values copied from the referenced entity into our entity up to date. If this bone is indexed, it’s recommended to leave this set to RelationalUpdateLevel.Always, as filtering/sorting by this bone will produce stale results.

    param RelationalUpdateLevel.Always:

    always update refkeys (old behavior). If the referenced entity is edited, ViUR will update this entity also (after a small delay, as these updates happen deferred)

    param RelationalUpdateLevel.OnRebuildSearchIndex:

    update refKeys only on rebuildSearchIndex. If the referenced entity changes, this entity will remain unchanged (this RelationalBone will still have the old values), but it can be updated by either by editing this entity or running a rebuildSearchIndex over our kind.

    param RelationalUpdateLevel.OnValueAssignment:

    update only if explicitly set. A rebuildSearchIndex will not trigger an update, this bone has to be explicitly modified (in an edit) to have it’s values updated

  • consistency (RelationalConsistency) –

    Can be used to implement SQL-like constrains on this relation. Possible values are:
    • RelationalConsistency.Ignore

      If the referenced entity gets deleted, this bone will not change. It will still reflect the old values. This will be even be preserved over edits, however if that referenced value is once deleted by the user (assigning a different value to this bone or removing that value of the list of relations if we are multiple) there’s no way of restoring it

    • RelationalConsistency.PreventDeletion

      Will prevent deleting the referenced entity as long as it’s selected in this bone (calling skel.delete() on the referenced entity will raise errors.Locked). It’s still (technically) possible to remove the underlying datastore entity using db.Delete manually, but this must not be used on a skeleton object as it will leave a whole bunch of references in a stale state.

    • RelationalConsistency.SetNull

      Will set this bone to None (or remove the relation from the list in case we are multiple) when the referenced entity is deleted.

    • RelationalConsistency.CascadeDeletion:

      (Dangerous!) Will delete this entity when the referenced entity is deleted. Warning: Unlike relational updates this will cascade. If Entity A references B with CascadeDeletion set, and B references C also with CascadeDeletion; if C gets deleted, both B and A will be deleted as well.

  • using (Optional[viur.core.skeleton.RelSkel]) –

Initialize a new RelationalBone.

Parameters:
  • kind (str) – KindName of the referenced property.

  • module (Optional[str]) – Name of the module which should be used to select entities of kind “type”. If not set, the value of “type” will be used (the kindName must match the moduleName)

  • refKeys (Optional[Iterable[str]]) – An iterable of properties to include from the referenced property. These properties will be available in the template without having to fetch the referenced property. Filtering is also only possible by properties named here!

  • parentKeys (Optional[Iterable[str]]) – An iterable of properties from the current skeleton to include. If mixing filtering by relational properties and properties of the class itself, these must be named here.

  • multiple – If True, allow referencing multiple Elements of the given class. (Eg. n:n-relation). Otherwise its n:1, (you can only select exactly one). It’s possible to use a unique constraint on this bone, allowing for at-most-1:1 or at-most-1:n relations. Instead of true, it’s also possible to use a :class:MultipleConstraints instead.

  • format (str) –

    Hint for the frontend how to display such an relation. This is now a python expression evaluated by safeeval on the client side. The following values will be passed to the expression

    param value:

    The value to display. This will be always a dict (= a single value) - even if the relation is multiple (in which case the expression is evaluated once per referenced entity)

    param structure:

    The structure of the skeleton this bone is part of as a dictionary as it’s transferred to the fronted by the admin/vi-render.

    param language:

    The current language used by the frontend in ISO2 code (eg. “de”). This will be always set, even if the project did not enable the multi-language feature.

  • updateLevel (RelationalUpdateLevel) –

    Indicates how ViUR should keep the values copied from the referenced entity into our entity up to date. If this bone is indexed, it’s recommended to leave this set to RelationalUpdateLevel.Always, as filtering/sorting by this bone will produce stale results.

    param RelationalUpdateLevel.Always:

    always update refkeys (old behavior). If the referenced entity is edited, ViUR will update this entity also (after a small delay, as these updates happen deferred)

    param RelationalUpdateLevel.OnRebuildSearchIndex:

    update refKeys only on rebuildSearchIndex. If the referenced entity changes, this entity will remain unchanged (this RelationalBone will still have the old values), but it can be updated by either by editing this entity or running a rebuildSearchIndex over our kind.

    param RelationalUpdateLevel.OnValueAssignment:

    update only if explicitly set. A rebuildSearchIndex will not trigger an update, this bone has to be explicitly modified (in an edit) to have it’s values updated

  • consistency (RelationalConsistency) –

    Can be used to implement SQL-like constrains on this relation.

    param RelationalConsistency.Ignore:

    If the referenced entity gets deleted, this bone will not change. It will still reflect the old values. This will be even be preserved over edits, however if that referenced value is once deleted by the user (assigning a different value to this bone or removing that value of the list of relations if we are multiple) there’s no way of restoring it

    param RelationalConsistency.PreventDeletion:

    Will prevent deleting the referenced entity as long as it’s selected in this bone (calling skel.delete() on the referenced entity will raise errors.Locked). It’s still (technically) possible to remove the underlying datastore entity using db.Delete manually, but this must not be used on a skeleton object as it will leave a whole bunch of references in a stale state.

    param RelationalConsistency.SetNull:

    Will set this bone to None (or remove the relation from the list in case we are multiple) when the referenced entity is deleted.

    param RelationalConsistency.CascadeDeletion:

    (Dangerous!) Will delete this entity when the referenced entity is deleted. Warning: Unlike relational updates this will cascade. If Entity A references B with CascadeDeletion set, and B references C also with CascadeDeletion; if C gets deleted, both B and A will be deleted as well.

  • using (Optional[viur.core.skeleton.RelSkel]) –

type = 'relational'
kind
setSystemInitialized()

Set the system initialized for the current class and cache the RefSkel and SkeletonInstance.

This method calls the superclass’s setSystemInitialized method and initializes the RefSkel and SkeletonInstance classes. The RefSkel is created from the current kind and refKeys, while the SkeletonInstance class is stored as a reference.

Return type:

None

_getSkels()

Retrieve the reference skeleton and the ‘using’ skeleton for the current RelationalBone instance.

This method returns a tuple containing the reference skeleton (RefSkel) and the ‘using’ skeleton (UsingSkel) associated with the current RelationalBone instance. The ‘using’ skeleton is only retrieved if the ‘using’ attribute is defined.

Returns:

A tuple containing the reference skeleton and the ‘using’ skeleton.

Return type:

tuple

singleValueUnserialize(val)

Restore a value, including the Rel- and Using-Skeleton, from the serialized data read from the datastore.

This method takes a serialized value from the datastore, deserializes it, and returns the corresponding value with restored RelSkel and Using-Skel. It also handles ViUR 2 compatibility by handling string values.

Parameters:

val (str or dict) – A JSON-encoded datastore property.

Returns:

The deserialized value with restored RelSkel and Using-Skel.

Return type:

dict

Raises:

AssertionError – If the deserialized value is not a dictionary.

serialize(skel, name, parentIndexed)

Serialize the RelationalBone for the given skeleton, updating relational locks as necessary.

This method serializes the RelationalBone values for a given skeleton and stores the serialized values in the skeleton’s dbEntity. It also updates the relational locks, adding new locks and removing old ones as needed.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance containing the values to be serialized.

  • name (str) – The name of the bone to be serialized.

  • parentIndexed (bool) – A flag indicating whether the parent bone is indexed.

Returns:

True if the serialization is successful, False otherwise.

Return type:

bool

Raises:

AssertionError – If a programming error is detected.

delete(skel, name)

Clear any outgoing relational locks when deleting a skeleton.

This method ensures that any outgoing relational locks are cleared when deleting a skeleton.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance being deleted.

  • name (str) – The name of the bone being deleted.

Raises:

Warning – If a referenced entry is missing despite the lock.

postSavedHandler(skel, boneName, key)

Handle relational updates after a skeleton is saved.

This method updates, removes, or adds relations between the saved skeleton and the referenced entities. It also takes care of updating the relational properties and consistency levels.

Parameters:
  • skel (SkeletonInstance) – The saved skeleton instance.

  • boneName (str) – The name of the relational bone.

  • key (google.cloud.datastore.key.Key) – The key of the saved skeleton instance.

Raises:

Warning – If a relation entry is corrupt and cannot be updated.

postDeletedHandler(skel, boneName, key)

Handle relational updates after a skeleton is deleted.

This method deletes all relations associated with the deleted skeleton and the referenced entities for the given relational bone.

Parameters:
  • skel (SkeletonInstance) – The deleted skeleton instance.

  • boneName (str) – The name of the relational bone.

  • key (google.cloud.datastore.key.Key) – The key of the deleted skeleton instance.

isInvalid(key)

Check if the given key is invalid for this relational bone.

This method always returns None, as the actual validation of the key is performed in other methods of the RelationalBone class.

Parameters:

key – The key to be checked for validity.

Returns:

None, as the actual validation is performed elsewhere.

parseSubfieldsFromClient()

Determine if the RelationalBone should parse subfields from the client.

This method returns True if the using attribute is not None, indicating that this RelationalBone has a using-skeleton, and its subfields should be parsed. Otherwise, it returns False.

Returns:

True if the using-skeleton is not None and subfields should be parsed, False otherwise.

Return type:

bool

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

_rewriteQuery(name, skel, dbFilter, rawFilter)

Rewrites a datastore query to operate on “viur-relations” instead of the original kind.

This method is needed to perform relational queries on n:m relations. It takes the original datastore query and rewrites it to target the “viur-relations” kind. It also adjusts filters and sort orders accordingly.

Parameters:
  • name (str) – The name of the bone.

  • skel (SkeletonInstance) – The skeleton instance the bone is a part of.

  • dbFilter (viur.core.db.Query) – The original datastore query to be rewritten.

  • rawFilter (dict) – The raw filter applied to the original datastore query.

Returns:

A tuple containing the name, skeleton, rewritten query, and raw filter.

Return type:

Tuple[str, ‘viur.core.skeleton.SkeletonInstance’, ‘viur.core.db.Query’, dict]

Raises:
  • NotImplementedError – If the original query contains multiple filters with “IN” or “!=” operators.

  • RuntimeError – If the filtering is invalid, e.g., using multiple key filters or querying properties not in parentKeys.

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Builds a datastore query by modifying the given filter based on the RelationalBone’s properties.

This method takes a datastore query and modifies it according to the relational bone properties. It also merges any related filters based on the ‘refKeys’ and ‘using’ attributes of the bone.

Parameters:
  • name (str) – The name of the bone.

  • skel (SkeletonInstance) – The skeleton instance the bone is a part of.

  • dbFilter (db.Query) – The original datastore query to be modified.

  • rawFilter (dict) – The raw filter applied to the original datastore query.

  • prefix (str) – Optional prefix to be applied to filter keys.

Returns:

The modified datastore query.

Return type:

db.Query

Raises:

RuntimeError – If the filtering is invalid, e.g., querying properties not in ‘refKeys’ or not a bone in ‘using’.

buildDBSort(name, skel, dbFilter, rawFilter)

Builds a datastore query by modifying the given filter based on the RelationalBone’s properties for sorting.

This method takes a datastore query and modifies its sorting behavior according to the relational bone properties. It also checks if the sorting is valid based on the ‘refKeys’ and ‘using’ attributes of the bone.

Parameters:
  • name (str) – The name of the bone.

  • skel (SkeletonInstance) – The skeleton instance the bone is a part of.

  • dbFilter (db.Query) – The original datastore query to be modified.

  • rawFilter (dict) – The raw filter applied to the original datastore query.

Returns:

The modified datastore query with updated sorting behavior.

Return type:

t.Optional[db.Query]

Raises:

RuntimeError – If the sorting is invalid, e.g., using properties not in ‘refKeys’ or not a bone in ‘using’.

filterHook(name, query, param, value)

Hook installed by buildDbFilter that rewrites filters added to the query to match the layout of the viur-relations index and performs sanity checks on the query.

This method rewrites and validates filters added to a datastore query after the buildDbFilter method has been executed. It ensures that the filters are compatible with the structure of the viur-relations index and checks if the query is possible.

Parameters:
  • name (str) – The name of the bone.

  • query (db.Query) – The datastore query to be modified.

  • param (str) – The filter parameter to be checked and potentially modified.

  • value – The value associated with the filter parameter.

Returns:

A tuple containing the modified filter parameter and its associated value, or None if the filter parameter is a key special property.

Return type:

Tuple[str, Any] or None

Raises:

RuntimeError – If the filtering is invalid, e.g., using properties not in ‘refKeys’ or ‘parentKeys’.

orderHook(name, query, orderings)

Hook installed by buildDbFilter that rewrites orderings added to the query to match the layout of the viur-relations index and performs sanity checks on the query.

This method rewrites and validates orderings added to a datastore query after the buildDbFilter method has been executed. It ensures that the orderings are compatible with the structure of the viur-relations index and checks if the query is possible.

Parameters:
  • name (str) – The name of the bone.

  • query (db.Query) – The datastore query to be modified.

  • orderings (List[Union[str, Tuple[str, db.SortOrder]]] or Tuple[Union[str, Tuple[str, db.SortOrder]]]) – A list or tuple of orderings to be checked and potentially modified.

Returns:

A list of modified orderings that are compatible with the viur-relations index.

Return type:

List[Union[str, Tuple[str, db.SortOrder]]]

Raises:

RuntimeError – If the ordering is invalid, e.g., using properties not in ‘refKeys’ or ‘parentKeys’.

refresh(skel, boneName)

Refreshes all values that might be cached from other entities in the provided skeleton.

This method updates the cached values for relational bones in the provided skeleton, which correspond to other entities. It fetches the updated values for the relational bone’s reference keys and replaces the cached values in the skeleton with the fetched values.

Parameters:
  • skel (SkeletonInstance) – The skeleton containing the bone to be refreshed.

  • boneName (str) – The name of the bone to be refreshed.

getSearchTags(skel, name)

Retrieves the search tags for the given RelationalBone in the provided skeleton.

This method iterates over the values of the relational bone and gathers search tags from the reference and using skeletons. It combines all the tags into a set to avoid duplicates.

Parameters:
  • skel (SkeletonInstance) – The skeleton containing the bone for which search tags are to be retrieved.

  • name (str) – The name of the bone for which search tags are to be retrieved.

Returns:

A set of search tags for the specified relational bone.

Return type:

Set[str]

createRelSkelFromKey(key, rel=None)

Creates a relSkel instance valid for this bone from the given database key.

This method retrieves the entity corresponding to the provided key from the database, unserializes it into a reference skeleton, and returns a dictionary containing the reference skeleton and optional relation data.

Parameters:
  • key (Union[str, viur.core.db.Key]) – The database key of the entity for which a relSkel instance is to be created.

  • None]rel (Union[dict,) – Optional relation data to be included in the resulting dictionary. Default is None.

  • key

  • rel (dict | None) –

Returns:

A dictionary containing a reference skeleton and optional relation data.

Return type:

dict

setBoneValue(skel, boneName, value, append, language=None)

Sets the value of the specified bone in the given skeleton. Sanity checks are performed to ensure the value is valid. If the value is invalid, no modifications are made.

Parameters:
  • skel (SkeletonInstance) – Dictionary with the current values from the skeleton we belong to.

  • boneName (str) – The name of the bone to be modified.

  • value (Any) – The value to be assigned. The type depends on the bone type.

  • append (bool) – If true, the given value is appended to the values of the bone instead of replacing it. Only supported on bones with multiple=True.

  • language (None | str) – Set/append for a specific language (optional). Required if the bone supports languages.

  • language

Returns:

True if the operation succeeded, False otherwise.

Return type:

bool

getReferencedBlobs(skel, name)

Retrieves the set of referenced blobs from the specified bone in the given skeleton instance.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance to extract the referenced blobs from.

  • name (str) – The name of the bone to retrieve the referenced blobs from.

Returns:

A set containing the unique blob keys referenced by the specified bone.

Return type:

Set[str]

getUniquePropertyIndexValues(valuesCache, name)

Generates unique property index values for the RelationalBone based on the referenced keys. Can be overridden if different behavior is required (e.g., examining values from prop:usingSkel).

Parameters:
  • valuesCache (dict) – The cache containing the current values of the bone.

  • name (str) – The name of the bone for which to generate unique property index values.

Returns:

A list containing the unique property index values for the specified bone.

Return type:

List[str]

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.RelationalConsistency

Bases: enum.Enum

An enumeration representing the different consistency strategies for handling stale relations in the RelationalBone class.

Ignore = 1

Ignore stale relations, which represents the old behavior.

PreventDeletion = 2

Lock the target object so that it cannot be deleted.

SetNull = 3

Drop the relation if the target object is deleted.

CascadeDeletion = 4

Warning

Delete this object also if the referenced entry is deleted (Dangerous!)

class core.bones.RelationalUpdateLevel

Bases: enum.Enum

An enumeration representing the different update levels for the RelationalBone class.

Always = 0

Always update the relational information, regardless of the context.

OnRebuildSearchIndex = 1

Update the relational information only when rebuilding the search index.

OnValueAssignment = 2

Update the relational information only when a new value is assigned to the bone.

class core.bones.SelectCountryBone(*, codes=ISO2, values=None, **kwargs)

Bases: viur.core.bones.select.SelectBone

A bone representing a country selection input field in a web application or form.

The SelectCountryBone is designed to provide a user-friendly way to select a country from a predefined list of countries. It inherits from the BaseBone class and extends it to support country-specific functionalities, such as displaying country names and handling country codes (e.g., ISO 3166-1 alpha-2 or alpha-3).

Params List[str] countries:

A list of countries supported by the bone, typically represented by their codes.

Initializes a new SelectBone.

Parameters:
  • defaultValue – key(s) of the values which will be checked by default.

  • values – dict of key->value pairs from which the user can choose from – or a callable that returns a dict.

  • translation_key_prefix – A prefix for the key of the translation object. It is empty by default, so that only the label (dict value) from the values is used. A static string or dynamic method can be used (like translation_key_prefix_bonename).

  • kwargs – Additional keyword arguments that will be passed to the superclass’ __init__ method.

type = 'select.country'
ISO2 = 2
ISO3 = 3
singleValueUnserialize(val)

Unserializes a single value, converting ISO country codes between ISO 3166-1 alpha-2 and alpha-3 if necessary.

This method takes a country code string (either ISO 3166-1 alpha-2 or alpha-3) and checks if a conversion is needed based on the self.codes attribute. If a conversion is required, it attempts to perform the conversion using the ISO3TOISO2 or ISO2TOISO3 dictionaries. If the conversion is successful, the converted code is returned; otherwise, the original value is returned.

Params val:

The value to be unserialized, typically a string representing an ISO country code.

Returns:

The unserialized value, either the original or converted ISO country code.

class core.bones.SelectBone(*, defaultValue=None, values=(), translation_key_prefix='', **kwargs)

Bases: viur.core.bones.base.BaseBone

A SelectBone is a bone which can take a value from a certain list of values. Inherits from the BaseBone class. The type attribute is set to “select”.

Initializes a new SelectBone.

Parameters:
  • defaultValue (Union[SelectBoneValue, SelectBoneMultiple, Dict[str, Union[SelectBoneMultiple, SelectBoneValue]], Callable[[viur.core.skeleton.SkeletonInstance, Self], Any]]) – key(s) of the values which will be checked by default.

  • values (dict | list | tuple | Callable | enum.EnumMeta) – dict of key->value pairs from which the user can choose from – or a callable that returns a dict.

  • translation_key_prefix (str | Callable[[Self], str]) – A prefix for the key of the translation object. It is empty by default, so that only the label (dict value) from the values is used. A static string or dynamic method can be used (like translation_key_prefix_bonename).

  • kwargs – Additional keyword arguments that will be passed to the superclass’ __init__ method.

type = 'select'
__getattribute__(item)

Overrides the default __getattribute__ method to handle the ‘values’ attribute dynamically. If the ‘_values’ attribute is callable, it will be called and the result will be stored in the ‘values’ attribute.

Parameters:

item (str) – The attribute name.

Returns:

The value of the specified attribute.

Raises:

AssertionError – If the resulting values are not of type dict or OrderedDict.

singleValueUnserialize(val)

Unserializes a single value of the bone from the stored database value.

Derived bone classes should overwrite this method to implement their own logic for unserializing single values. The unserialized value should be suitable for use in the application logic.

singleValueSerialize(val, skel, name, parentIndexed)

Serializes a single value of the bone for storage in the database.

Derived bone classes should overwrite this method to implement their own logic for serializing single values. The serialized value should be suitable for storage in the database.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) –

  • name (str) –

  • parentIndexed (bool) –

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

core.bones.translation_key_prefix_skeleton_bonename(bones_instance)

Generate a translation key prefix based on the skeleton name

Parameters:

bones_instance (viur.core.bones.base.BaseBone) –

Return type:

str

core.bones.translation_key_prefix_bonename(bones_instance)

Generate a translation key prefix based on the skeleton and bone name

Parameters:

bones_instance (viur.core.bones.base.BaseBone) –

Return type:

str

class core.bones.SortIndexBone(*, defaultValue=lambda *args, **kwargs: ..., descr='SortIndex', precision=8, **kwargs)

Bases: viur.core.bones.numeric.NumericBone

The SortIndexBone class is specifically designed to handle sorting indexes for data elements, which are numeric values that determine the order of these elements. It inherits from the NumericBone.

Parameters:
  • defaultValue (int | float) – A default value for the bone, which is a function that returns the current time by default. This parameter accepts either an integer or a floating-point number.

  • descr (str) – A short description of the bone, set to “SortIndex” by default.

  • precision (int) – The precision of the numeric value, determining the number of decimal places allowed. The default value is 8.

  • kwargs (dict) – Additional keyword arguments that can be passed to the parent NumericBone class.

  • defaultValue

Initializes a new NumericBone.

type = 'numeric.sortindex'
class core.bones.SpatialBone(*, boundsLat, boundsLng, gridDimensions, **kwargs)

Bases: viur.core.bones.base.BaseBone

The “SpatialBone” is a specific type of data structure designed to handle spatial data, such as geographical coordinates or geometries. This bone would typically be used for representing and storing location-based data, like the coordinates of a point of interest on a map or the boundaries of a geographic region. This feature allows querying elements near a specific location. Before using, designate the map region for which the index should be constructed. To ensure the best accuracy, minimize the region size; using the entire world is not feasible since boundary wraps are not executed. GridDimensions indicates the number of sub-regions the map will be partitioned into. Results beyond the size of these sub-regions will not be considered during searches by this algorithm.

Note

Example: When using this feature to find the nearest pubs, the algorithm could be set to consider results within 100km but not those 500km away. Setting the sub-region size to roughly 100km in width and height allows the algorithm to exclude results further than 200km away at the database-query-level, significantly enhancing performance and reducing query costs.

Example region: Germany: `boundsLat=(46.988, 55.022), boundsLng=(4.997, 15.148)`

Parameters:
  • boundsLat (tuple[float, float]) – The outer bounds (Latitude) of the region we will search in

  • boundsLng (tuple[float, float]) – The outer bounds (Longitude) of the region we will search in

  • gridDimensions (tuple[int, int]) – (Tuple[int, int]) The number of sub-regions the map will be divided in

  • boundsLat

  • boundsLng

Initializes a new SpatialBone.

Parameters:
  • boundsLat (tuple[float, float]) – Outer bounds (Latitude) of the region we will search in.

  • boundsLng (tuple[float, float]) – Outer bounds (Longitude) of the region we will search in.

  • gridDimensions (tuple[int, int]) – Number of sub-regions the map will be divided in

type = 'spatial'
getGridSize()

Calculate and return the size of the sub-regions in terms of fractions of latitude and longitude.

Returns:

A tuple containing the size of the sub-regions as (fractions-of-latitude, fractions-of-longitude)

Return type:

(float, float)

isInvalid(value)

Validate if the given point (latitude, longitude) falls within the specified boundaries. Rejects all values outside the defined region.

Parameters:

value (tuple[float, float]) – A tuple containing the location of the entry as (latitude, longitude)

Returns:

An error description if the value is invalid or False if the value is valid

Return type:

str | bool

singleValueSerialize(value, skel, name, parentIndexed)

Serialize a single value (latitude, longitude) for storage. If the bone is indexed, calculate and add tile information for efficient querying.

Parameters:
  • value – A tuple containing the location of the entry as (latitude, longitude)

  • skel (SkeletonInstance) – The instance of the Skeleton this bone is attached to

  • name (str) – The name of this bone

  • parentIndexed (bool) – A boolean indicating if the parent bone is indexed

Returns:

A dictionary containing the serialized data, including coordinates and tile information (if indexed)

Return type:

dict | None

singleValueUnserialize(val)

Deserialize a single value (latitude, longitude) from the stored data.

Parameters:

val – A dictionary containing the serialized data, including coordinates

Returns:

A tuple containing the location of the entry as (latitude, longitude)

Return type:

Tuple[float, float] | None

parseSubfieldsFromClient()

Determines if subfields (latitude and longitude) should be parsed from the client.

Returns:

Always returns True, as latitude and longitude are required

Return type:

bool

isEmpty(value)

Check if the given raw value is considered empty (either not present or equal to the empty value).

Parameters:

value (Any) – The raw value to be checked

Returns:

True if the raw value is considered empty, False otherwise

Return type:

bool

getEmptyValue()

Returns an empty value for the bone, which represents an invalid position. Use 91.0, 181.0 as a special marker for empty, as they are both out of range for Latitude (-90, +90) and Longitude (-180, 180), but will be accepted by Vi and Admin.

Returns:

A tuple representing an empty value for this bone (91.0, 181.0)

Return type:

Tuple[float, float]

singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Parses the client’s search filter specified in their request and converts it into a format understood by the datastore.

  • Ignore filters that do not target this bone.

  • Safely handle malformed data in rawFilter (this parameter is directly controlled by the client).

For detailed information on how this geo-spatial search works, see the ViUR documentation.

Parameters:
  • name (str) – The property name this bone has in its Skeleton (not the description!)

  • skel (SkeletonInstance) – The skeleton this bone is part of

  • dbFilter (db.Query) – The current viur.core.db.Query instance to which the filters should be applied

  • rawFilter (dict) – The dictionary of filters the client wants to have applied

  • prefix (Optional[str]) – Optional string, specifying a prefix for the bone’s name (default is None)

Returns:

The modified viur.core.db.Query instance

Return type:

db.Query

calculateInternalMultiQueryLimit(dbQuery, targetAmount)

Provides guidance to viur.core.db.Query on the number of entries that should be fetched in each subquery.

Parameters:
  • dbQuery (viur.core.db.Query) – The viur.core.db.Query instance

  • targetAmount (int) – The desired number of entries to be returned from the db.Query

Returns:

The number of elements db.Query should fetch for each subquery

Return type:

int

customMultiQueryMerge(name, lat, lng, dbFilter, result, targetAmount)

Randomly returns ‘targetAmount’ elements from ‘result’.

Parameters:
  • name (str) – The property-name this bone has in its Skeleton (not the description!)

  • lat – Latitude of the reference point

  • lng – Longitude of the reference point

  • dbFilter (viur.core.db.Query) – The db.Query instance calling this function

  • result (list[viur.core.db.Entity]) – The list of results for each subquery that was executed

  • targetAmount (int) – The desired number of results to be returned from db.Query

Returns:

List of elements to be returned from db.Query

Return type:

List[db.Entity]

setBoneValue(skel, boneName, value, append, language=None)

Sets the value of the bone to the provided ‘value’. Sanity checks are performed; if the value is invalid, the bone value will revert to its original (default) value and the function will return False.

Parameters:
  • skel (SkeletonInstance) – Dictionary with the current values from the skeleton the bone belongs to

  • boneName (str) – The name of the bone that should be modified

  • value (Any) – The value that should be assigned. Its type depends on the type of the bone

  • append (bool) – If True, the given value will be appended to the existing bone values instead of replacing them. Only supported on bones with multiple=True

  • language (None | str) – Optional, the language of the value if the bone is language-aware

Returns:

A boolean indicating whether the operation succeeded or not

Return type:

bool

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.StringBone(*, caseSensitive=True, max_length=254, min_length=None, natural_sorting=False, **kwargs)

Bases: viur.core.bones.base.BaseBone

The “StringBone” represents a data field that contains text values.

Initializes a new StringBone.

Parameters:
  • caseSensitive (bool) – When filtering for values in this bone, should it be case-sensitive?

  • max_length (int | None) – The maximum length allowed for values of this bone. Set to None for no limitation.

  • min_length (int | None) – The minimum length allowed for values of this bone. Set to None for no limitation.

  • natural_sorting (bool | Callable) – Allows a more natural sorting than the default sorting on the plain values. This uses the .sort_idx property. True enables sorting according to DIN 5007 Variant 2. With passing a callable, a custom transformer method can be set that creates the value for the index property.

  • kwargs – Inherited arguments from the BaseBone.

type = 'str'
type_coerce_single_value(value)

Convert a value to a string (if not already)

Converts a value that is not a string into a string if a meaningful conversion is possible (simple data types only).

Parameters:

value (Any) –

Return type:

str

singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value of this data field for storage in the database.

Parameters:
  • value (Any) – The value to serialize. It should be a str value, if not it is forced with type_coerce_single_value().

  • skel (core.skeleton.SkeletonInstance) – The skeleton instance that this data field belongs to.

  • name (str) – The name of this data field.

  • parentIndexed (bool) – A boolean value indicating whether the parent object has an index on this data field or not.

Returns:

The serialized value.

Return type:

str | DB_TYPE_INDEXED

singleValueUnserialize(value)

Unserializes a single value of this data field from the database.

Parameters:

value (str | DB_TYPE_INDEXED) – The serialized value to unserialize.

Returns:

The unserialized value.

Return type:

str

getEmptyValue()

Returns the empty value for this data field.

Returns:

An empty string.

Return type:

str

isEmpty(value)

Determines whether a value for this data field is empty or not.

Parameters:

value – The value to check for emptiness.

Returns:

A boolean value indicating whether the value is empty or not.

isInvalid(value)

Returns None if the value would be valid for this bone, an error-message otherwise.

Parameters:

value (Any) –

Return type:

str | None

singleValueFromClient(value, skel, bone_name, client_data)

Returns None and the escaped value if the value would be valid for this bone, otherwise the empty value and an error-message.

buildDBFilter(name, skel, dbFilter, rawFilter, prefix=None)

Builds and returns a database filter for this data field based on the provided raw filter data.

Parameters:
  • name (str) – The name of this data field.

  • skel (core.skeleton.SkeletonInstance) – The skeleton instance that this data field belongs to.

  • dbFilter (viur.core.db.Query) – The database filter to add query clauses to.

  • rawFilter (dict) – A dictionary containing the raw filter data for this data field.

  • prefix (Optional[str]) – An optional prefix to add to the query clause.

Returns:

The database filter with the added query clauses.

Return type:

viur.core.db.Query

buildDBSort(name, skel, dbFilter, rawFilter)

Build a DB sort based on the specified name and a raw filter.

Parameters:
  • name (str) – The name of the attribute to sort by.

  • skel (core.skeleton.SkeletonInstance) – A SkeletonInstance object.

  • dbFilter (viur.core.db.Query) – A Query object representing the current DB filter.

  • rawFilter (dict) – A dictionary containing the raw filter.

Returns:

The Query object with the specified sort applied.

Return type:

Optional[viur.core.db.Query]

natural_sorting(value)

Implements a default natural sorting transformer.

The sorting is according to DIN 5007 Variant 2 and sets ö and oe, etc. equal.

Parameters:

value (str | None) –

Return type:

str | None

getSearchTags(skel, name)

Returns a set of lowercased words that represent searchable tags for the given bone.

Parameters:
Returns:

A set of lowercased words representing searchable tags.

Return type:

set[str]

getUniquePropertyIndexValues(skel, name)

Returns a list of unique index values for a given property name.

Parameters:
Returns:

A list of unique index values for the property.

Raises:

NotImplementedError – If the StringBone has languages and the implementation for this case is not yet defined.

Return type:

list[str]

refresh(skel, bone_name)

Refresh all values we might have cached from other entities.

Parameters:
Return type:

None

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.TextBone(*, validHtml=__undefinedC__, max_length=200000, srcSet=None, indexed=False, **kwargs)

Bases: viur.core.bones.base.BaseBone

A bone for storing and validating HTML or plain text content. Can be configured to allow only specific HTML tags and attributes, and enforce a maximum length. Supports the use of srcset for embedded images.

Parameters:
  • validHtml (None | dict) – A dictionary containing allowed HTML tags and their attributes. Defaults to _defaultTags. Must be a structured like :prop:_defaultTags

  • max_length (int) – The maximum allowed length for the content. Defaults to 200000.

  • languages – If set, this bone can store a different content for each language

  • srcSet (Optional[dict[str, list]]) – An optional dictionary containing width and height for srcset generation. Must be a dict of “width”: [List of Ints], “height”: [List of Ints], eg {“height”: [720, 1080]}

  • indexed (bool) – Whether the content should be indexed for searching. Defaults to False.

  • kwargs – Additional keyword arguments to be passed to the base class constructor.

  • validHtml – If set, must be a structure like :prop:_defaultTags

  • languages – If set, this bone can store a different content for each language

  • max_length – Limit content to max_length bytes

  • indexed – Must not be set True, unless you limit max_length accordingly

  • srcSet – If set, inject srcset tags to embedded images. Must be a dict of “width”: [List of Ints], “height”: [List of Ints], eg {“height”: [720, 1080]}

class __undefinedC__
type = 'text'
singleValueSerialize(value, skel, name, parentIndexed)

Serializes a single value of the TextBone instance for storage.

This method takes the value as-is without any additional processing, since it’s already stored in a format suitable for serialization.

Parameters:
singleValueFromClient(value, skel, bone_name, client_data)

Load a single value from a client

Parameters:
  • value – The single value which should be loaded.

  • skel – The SkeletonInstance where the value should be loaded into.

  • bone_name – The bone name of this bone in the SkeletonInstance.

  • client_data – The data taken from the client, a dictionary with usually bone names as key

Returns:

A tuple. If the value is valid, the first element is the parsed value and the second is None. If the value is invalid or not parseable, the first element is a empty value and the second a list of ReadFromClientError.

getEmptyValue()

Returns an empty value for the TextBone instance.

This method is used to represent an empty or unset value for the TextBone.

return: An empty string. :rtype: str

isInvalid(value)

Checks if the given value is valid for this TextBone instance.

This method checks whether the given value is valid according to the TextBone’s constraints (e.g., not None and within the maximum length).

Parameters:

value – The value to be checked for validity.

Returns:

Returns None if the value is valid, or an error message string otherwise.

Return type:

Optional[str]

getReferencedBlobs(skel, name)

Extracts and returns the blob keys of referenced files in the HTML content of the TextBone instance.

This method parses the HTML content of the TextBone to identify embedded images or file hrefs, collects their blob keys, and ensures that they are not deleted even if removed from the file browser, preventing broken links or images in the TextBone content.

Parameters:
  • skel (SkeletonInstance) – A SkeletonInstance object containing the data of an entry.

  • name (str) – The name of the TextBone for which to find referenced blobs.

Returns:

A set containing the blob keys of the referenced files in the TextBone’s HTML content.

Return type:

Set[str]

refresh(skel, boneName)

Re-parses the text content of the TextBone instance to rebuild the src-set if necessary.

This method is useful when the src-set configuration has changed and needs to be applied to the existing HTML content. It re-parses the content and updates the src-set attributes accordingly.

Parameters:
  • skel (SkeletonInstance) – A SkeletonInstance object containing the data of an entry.

  • boneName (str) – The name of the TextBone for which to refresh the src-set.

Return type:

None

getSearchTags(skel, name)

Extracts search tags from the text content of a TextBone.

This method iterates over the values of the TextBone in the given skeleton, and for each non-empty value, it tokenizes the text by lines and words. Then, it adds the lowercase version of each word to a set of search tags, which is returned at the end.

Parameters:
  • skel (viur.core.skeleton.SkeletonInstance) – A SkeletonInstance containing the TextBone.

  • name (str) – The name of the TextBone in the skeleton.

Returns:

A set of unique search tags (lowercase words) extracted from the text content of the TextBone.

Return type:

set[str]

getUniquePropertyIndexValues(valuesCache, name)

Retrieves the unique property index values for the TextBone.

If the TextBone supports multiple languages, this method raises a NotImplementedError, as it’s unclear whether each language should be kept distinct or not. Otherwise, it calls the superclass’s getUniquePropertyIndexValues method to retrieve the unique property index values.

Parameters:
  • valuesCache (dict) – A dictionary containing the cached values for the TextBone.

  • name (str) – The name of the TextBone.

Returns:

A list of unique property index values for the TextBone.

Raises:

NotImplementedError – If the TextBone supports multiple languages.

Return type:

list[str]

structure()

Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types.

Return type:

dict

class core.bones.TreeLeafBone(**kwargs)

Bases: viur.core.bones.relational.RelationalBone

TreeLeafBone is a subclass of RelationalBone specifically designed to represent a leaf node in a tree-like data structure. It provides an additional level of hierarchy and organization for relational data in ViUR applications.

Initialize a new RelationalBone.

Parameters:
  • kind – KindName of the referenced property.

  • module – Name of the module which should be used to select entities of kind “type”. If not set, the value of “type” will be used (the kindName must match the moduleName)

  • refKeys – An iterable of properties to include from the referenced property. These properties will be available in the template without having to fetch the referenced property. Filtering is also only possible by properties named here!

  • parentKeys – An iterable of properties from the current skeleton to include. If mixing filtering by relational properties and properties of the class itself, these must be named here.

  • multiple – If True, allow referencing multiple Elements of the given class. (Eg. n:n-relation). Otherwise its n:1, (you can only select exactly one). It’s possible to use a unique constraint on this bone, allowing for at-most-1:1 or at-most-1:n relations. Instead of true, it’s also possible to use a :class:MultipleConstraints instead.

  • format

    Hint for the frontend how to display such an relation. This is now a python expression evaluated by safeeval on the client side. The following values will be passed to the expression

    param value:

    The value to display. This will be always a dict (= a single value) - even if the relation is multiple (in which case the expression is evaluated once per referenced entity)

    param structure:

    The structure of the skeleton this bone is part of as a dictionary as it’s transferred to the fronted by the admin/vi-render.

    param language:

    The current language used by the frontend in ISO2 code (eg. “de”). This will be always set, even if the project did not enable the multi-language feature.

  • updateLevel

    Indicates how ViUR should keep the values copied from the referenced entity into our entity up to date. If this bone is indexed, it’s recommended to leave this set to RelationalUpdateLevel.Always, as filtering/sorting by this bone will produce stale results.

    param RelationalUpdateLevel.Always:

    always update refkeys (old behavior). If the referenced entity is edited, ViUR will update this entity also (after a small delay, as these updates happen deferred)

    param RelationalUpdateLevel.OnRebuildSearchIndex:

    update refKeys only on rebuildSearchIndex. If the referenced entity changes, this entity will remain unchanged (this RelationalBone will still have the old values), but it can be updated by either by editing this entity or running a rebuildSearchIndex over our kind.

    param RelationalUpdateLevel.OnValueAssignment:

    update only if explicitly set. A rebuildSearchIndex will not trigger an update, this bone has to be explicitly modified (in an edit) to have it’s values updated

  • consistency

    Can be used to implement SQL-like constrains on this relation.

    param RelationalConsistency.Ignore:

    If the referenced entity gets deleted, this bone will not change. It will still reflect the old values. This will be even be preserved over edits, however if that referenced value is once deleted by the user (assigning a different value to this bone or removing that value of the list of relations if we are multiple) there’s no way of restoring it

    param RelationalConsistency.PreventDeletion:

    Will prevent deleting the referenced entity as long as it’s selected in this bone (calling skel.delete() on the referenced entity will raise errors.Locked). It’s still (technically) possible to remove the underlying datastore entity using db.Delete manually, but this must not be used on a skeleton object as it will leave a whole bunch of references in a stale state.

    param RelationalConsistency.SetNull:

    Will set this bone to None (or remove the relation from the list in case we are multiple) when the referenced entity is deleted.

    param RelationalConsistency.CascadeDeletion:

    (Dangerous!) Will delete this entity when the referenced entity is deleted. Warning: Unlike relational updates this will cascade. If Entity A references B with CascadeDeletion set, and B references C also with CascadeDeletion; if C gets deleted, both B and A will be deleted as well.

type = 'relational.tree.leaf'
class core.bones.TreeNodeBone(*, consistency=RelationalConsistency.Ignore, format='$(dest.name)', kind=None, module=None, parentKeys={'name'}, refKeys={'name'}, updateLevel=RelationalUpdateLevel.Always, using=None, **kwargs)

Bases: viur.core.bones.relational.RelationalBone

TreeNodeBone is a subclass of RelationalBone specifically designed to represent an intermediate node in a tree-like data structure. It provides a way to define hierarchical relationships between entities in a ViUR application.

The TreeNodeBone is of type “relational.tree.node”, which distinguishes it from other RelationalBone subclasses.

Initialize a new RelationalBone.

Parameters:
  • kind (str) – KindName of the referenced property.

  • module (Optional[str]) – Name of the module which should be used to select entities of kind “type”. If not set, the value of “type” will be used (the kindName must match the moduleName)

  • refKeys (Optional[Iterable[str]]) – An iterable of properties to include from the referenced property. These properties will be available in the template without having to fetch the referenced property. Filtering is also only possible by properties named here!

  • parentKeys (Optional[Iterable[str]]) – An iterable of properties from the current skeleton to include. If mixing filtering by relational properties and properties of the class itself, these must be named here.

  • multiple – If True, allow referencing multiple Elements of the given class. (Eg. n:n-relation). Otherwise its n:1, (you can only select exactly one). It’s possible to use a unique constraint on this bone, allowing for at-most-1:1 or at-most-1:n relations. Instead of true, it’s also possible to use a :class:MultipleConstraints instead.

  • format (str) –

    Hint for the frontend how to display such an relation. This is now a python expression evaluated by safeeval on the client side. The following values will be passed to the expression

    param value:

    The value to display. This will be always a dict (= a single value) - even if the relation is multiple (in which case the expression is evaluated once per referenced entity)

    param structure:

    The structure of the skeleton this bone is part of as a dictionary as it’s transferred to the fronted by the admin/vi-render.

    param language:

    The current language used by the frontend in ISO2 code (eg. “de”). This will be always set, even if the project did not enable the multi-language feature.

  • updateLevel (RelationalUpdateLevel) –

    Indicates how ViUR should keep the values copied from the referenced entity into our entity up to date. If this bone is indexed, it’s recommended to leave this set to RelationalUpdateLevel.Always, as filtering/sorting by this bone will produce stale results.

    param RelationalUpdateLevel.Always:

    always update refkeys (old behavior). If the referenced entity is edited, ViUR will update this entity also (after a small delay, as these updates happen deferred)

    param RelationalUpdateLevel.OnRebuildSearchIndex:

    update refKeys only on rebuildSearchIndex. If the referenced entity changes, this entity will remain unchanged (this RelationalBone will still have the old values), but it can be updated by either by editing this entity or running a rebuildSearchIndex over our kind.

    param RelationalUpdateLevel.OnValueAssignment:

    update only if explicitly set. A rebuildSearchIndex will not trigger an update, this bone has to be explicitly modified (in an edit) to have it’s values updated

  • consistency (RelationalConsistency) –

    Can be used to implement SQL-like constrains on this relation.

    param RelationalConsistency.Ignore:

    If the referenced entity gets deleted, this bone will not change. It will still reflect the old values. This will be even be preserved over edits, however if that referenced value is once deleted by the user (assigning a different value to this bone or removing that value of the list of relations if we are multiple) there’s no way of restoring it

    param RelationalConsistency.PreventDeletion:

    Will prevent deleting the referenced entity as long as it’s selected in this bone (calling skel.delete() on the referenced entity will raise errors.Locked). It’s still (technically) possible to remove the underlying datastore entity using db.Delete manually, but this must not be used on a skeleton object as it will leave a whole bunch of references in a stale state.

    param RelationalConsistency.SetNull:

    Will set this bone to None (or remove the relation from the list in case we are multiple) when the referenced entity is deleted.

    param RelationalConsistency.CascadeDeletion:

    (Dangerous!) Will delete this entity when the referenced entity is deleted. Warning: Unlike relational updates this will cascade. If Entity A references B with CascadeDeletion set, and B references C also with CascadeDeletion; if C gets deleted, both B and A will be deleted as well.

  • using (Optional[viur.core.skeleton.RelSkel]) –

type = 'relational.tree.node'
class core.bones.UserBone(*, creationMagic=False, descr='User', format='$(dest.lastname), $(dest.firstname) ($(dest.name))', kind='user', readOnly=False, refKeys=('key', 'name', 'firstname', 'lastname'), updateMagic=False, visible=None, **kwargs)

Bases: viur.core.bones.relational.RelationalBone

A specialized relational bone for handling user references. Extends the functionality of viur.core.bones.relational.RelationalBone to include support for creation and update magic, and comes with a predefined descr, format, kind and refKeys setting.

Initializes a new UserBone.

Parameters:
  • creationMagic (bool) – If True, the bone will automatically store the creating user when a new entry is added.

  • updateMagic (bool) – If True, the bone will automatically store the last user who updated the entry.

  • descr (str) –

  • format (str) –

  • kind (str) –

  • readOnly (bool) –

  • refKeys (Iterable[str]) –

  • visible (Optional[bool]) –

Raises:

ValueError – If the bone is multiple=True and creation/update magic is set.

performMagic(skel, key, isAdd, *args, **kwargs)

Perform the magic operation on the bone value.

If updateMagic is enabled or creationMagic is enabled and the operation is an addition, the bone will store the current user’s key.

Parameters:
  • skel (SkeletonInstance) – The skeleton instance to operate on.

  • key (str) – The key of the bone in the skeleton.

  • isAdd (bool) – If True, the operation is an addition. Otherwise, it is an update.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Returns:

True if the magic operation was successful, False otherwise.

Return type:

bool