:py:mod:`core.bones` ==================== .. py:module:: core.bones Submodules ---------- .. toctree:: :titlesonly: :maxdepth: 1 base/index.rst boolean/index.rst captcha/index.rst color/index.rst credential/index.rst date/index.rst email/index.rst file/index.rst json/index.rst key/index.rst numeric/index.rst password/index.rst randomslice/index.rst raw/index.rst record/index.rst relational/index.rst select/index.rst selectcountry/index.rst sortindex/index.rst spatial/index.rst string/index.rst text/index.rst treeleaf/index.rst treenode/index.rst user/index.rst Package Contents ---------------- Classes ~~~~~~~ .. autoapisummary:: core.bones.BaseBone core.bones.Compute core.bones.ComputeInterval core.bones.ComputeMethod core.bones.MultipleConstraints core.bones.ReadFromClientError core.bones.ReadFromClientErrorSeverity core.bones.UniqueLockMethod core.bones.UniqueValue core.bones.BooleanBone core.bones.CaptchaBone core.bones.ColorBone core.bones.CredentialBone core.bones.DateBone core.bones.EmailBone core.bones.FileBone core.bones.JsonBone core.bones.KeyBone core.bones.NumericBone core.bones.PasswordBone core.bones.RandomSliceBone core.bones.RawBone core.bones.RecordBone core.bones.RelationalBone core.bones.RelationalConsistency core.bones.RelationalUpdateLevel core.bones.SelectCountryBone core.bones.SelectBone core.bones.SortIndexBone core.bones.SpatialBone core.bones.StringBone core.bones.TextBone core.bones.TreeLeafBone core.bones.TreeNodeBone core.bones.UserBone Functions ~~~~~~~~~ .. autoapisummary:: core.bones.translation_key_prefix_skeleton_bonename core.bones.translation_key_prefix_bonename .. py:class:: BaseBone(*, compute = None, defaultValue = None, descr = '', getEmptyValueFunc = None, indexed = True, isEmptyFunc = None, languages = None, multiple = False, params = None, readOnly = None, required = False, searchable = False, type_suffix = '', unique = None, vfunc = None, visible = True) Bases: :py:obj:`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. :param descr: Textual, human-readable description of that bone. Will be translated. :param defaultValue: If set, this bone will be preinitialized with this value :param required: 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. :param multiple: If True, multiple values can be given. (ie. n:m relations instead of n:1) :param searchable: If True, this bone will be included in the fulltext search. Can be used without the need of also been indexed. :param type_suffix: Allows to specify an optional suffix for the bone-type, for bone customization :param vfunc: 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. :param readOnly: 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. :param visible: 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) :param compute: If set, the bone's value will be computed in the given method. .. NOTE:: The kwarg 'multiple' is not supported by all bones Initializes a new Bone. .. py:attribute:: type :value: 'hidden' .. py:attribute:: isClonedInstance :value: False .. py:attribute:: skel_cls Skeleton class to which this bone instance belongs .. py:attribute:: name Name of this bone (attribute name in the skeletons containing this bone) .. py:method:: __set_name__(owner, name) .. py:method:: setSystemInitialized() Can be overridden to initialize properties that depend on the Skeleton system being initialized .. py:method:: 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. .. py:method:: 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 .. py:method:: 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. :return: The default value of the bone, which can be of any data type. .. py:method:: 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. .. py:method:: __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. :param key: A string representing the attribute name. :param value: The value to be assigned to the attribute. :raises AttributeError: If a protected attribute is attempted to be modified after its initial assignment. .. py:method:: 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. :param name: A string representing the bone's name. :param data: A dictionary containing the raw data from the client. :param multiple: A boolean indicating whether the bone supports multiple values. :param languages: An optional list of strings representing the supported languages (default: None). :param collectSubfields: A boolean indicating whether to collect data for subfields (default: False). :return: A dictionary containing the collected raw client data. .. py:method:: 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. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: 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. :param skel: A SkeletonInstance object where the values should be loaded. :param name: A string representing the bone's name. :param data: A dictionary containing the raw data from the client. :return: None if no errors occurred, otherwise a list of ReadFromClientError objects. .. py:method:: _get_single_destinct_hash(value) Returns a distinct hash value for a single entry of this bone. The returned value must be hashable. .. py:method:: _get_destinct_hash(value) Returns a distinct hash value for this bone. The returned value must be hashable. .. py:method:: _validate_multiple_contraints(constraints, 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. :param constraints: The MultipleConstraints definition to apply. :param skel: A SkeletonInstance object where the values should be validated. :param name: A string representing the bone's name. :return: A list of ReadFromClientError objects for each constraint violation. .. py:method:: 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. .. py:method:: serialize(skel, name, parentIndexed) Serializes this bone into a format that can be written into the datastore. :param skel: A SkeletonInstance object containing the values to be serialized. :param name: A string representing the property name of the bone in its Skeleton (not the description). :param parentIndexed: A boolean indicating whether the parent bone is indexed. :return: A boolean indicating whether the serialization was successful. .. py:method:: 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. .. py:method:: 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. :param skel: A SkeletonInstance object containing the values to be deserialized. :param name: The property name of the bone in its Skeleton (not the description). :returns: True if deserialization is successful, False otherwise. .. py:method:: delete(skel, name) Like postDeletedHandler, but runs inside the transaction .. py:method:: 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) :param name: The property-name this bone has in its Skeleton (not the description!) :param skel: The :class:`viur.core.db.Query` this bone is part of :param dbFilter: The current :class:`viur.core.db.Query` instance the filters should be applied to :param rawFilter: The dictionary of filters the client wants to have applied :returns: The modified :class:`viur.core.db.Query` .. py:method:: 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! :param name: The property-name this bone has in its Skeleton (not the description!) :param skel: The :class:`viur.core.skeleton.Skeleton` instance this bone is part of :param dbFilter: The current :class:`viur.core.db.Query` instance the filters should be applied to :param rawFilter: The dictionary of filters the client wants to have applied :returns: The modified :class:`viur.core.db.Query`, None if the query is unsatisfiable. .. py:method:: _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. :param value: The value to be hashed, which can be a string, integer, or a float. :return: A list containing a string representation of the hashed value. If the bone is multiple, the list may contain more than one hashed value. .. py:method:: 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. :param skel: A SkeletonInstance object representing the current skeleton. :param name: The property-name of the bone in the skeleton for which the unique property index values are required (not the description!). :return: 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. .. py:method:: getReferencedBlobs(skel, name) Returns a set of blob keys referenced from this bone .. py:method:: 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. .. py:method:: postSavedHandler(skel, boneName, key) Can be overridden to perform further actions after the main entity has been written. :param boneName: Name of this bone :param skel: The skeleton this bone belongs to :param key: The (new?) Database Key we've written to .. py:method:: postDeletedHandler(skel, boneName, key) Can be overridden to perform further actions after the main entity has been deleted. :param skel: The skeleton this bone belongs to :param boneName: Name of this bone :param key: The old Database Key of the entity we've deleted .. py:method:: refresh(skel, boneName) Refresh all values we might have cached from other entities. .. py:method:: mergeFrom(valuesCache, boneName, otherSkel) Merges the values from another skeleton instance into the current instance, given that the bone types match. :param valuesCache: A dictionary containing the cached values for each bone in the skeleton. :param boneName: The property-name of the bone in the skeleton whose values are to be merged. :param otherSkel: 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. .. py:method:: 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. :param skel: The SkeletonInstance object representing the skeleton to which the bone belongs. :param boneName: The property-name of the bone in the skeleton whose value should be set or modified. :param value: The value to be assigned. Its type depends on the type of the bone. :param append: If True, the given value is appended to the bone's values instead of replacing it. Only supported for bones with multiple=True. :param language: The language code for which the value should be set or appended, if the bone supports languages. :return: A boolean indicating whether the operation was successful or not. 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. .. py:method:: 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. :param skel: The skeleton instance where the values should be loaded from. This is an instance of a class derived from `viur.core.skeleton.SkeletonInstance`. :param name: 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. :return: A set of strings, extracted from the bone value. If the bone value doesn't have any searchable content, an empty set is returned. .. py:method:: 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. :param skel: The skeleton instance where the values should be loaded from. This is an instance of a class derived from `viur.core.skeleton.SkeletonInstance`. :param name: 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. :return: 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. .. py:method:: _compute(skel, bone_name) Performs the evaluation of a bone configured as compute .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: Compute .. py:attribute:: fn :type: callable .. py:attribute:: interval :type: ComputeInterval .. py:attribute:: raw :type: bool :value: True .. py:class:: ComputeInterval .. py:attribute:: method :type: ComputeMethod .. py:attribute:: lifetime :type: datetime.timedelta .. py:class:: ComputeMethod Bases: :py:obj:`enum.Enum` Generic enumeration. Derive from this class to define new enumerations. .. py:attribute:: Always :value: 0 .. py:attribute:: Lifetime :value: 1 .. py:attribute:: Once :value: 2 .. py:attribute:: OnWrite :value: 3 .. py:class:: MultipleConstraints The MultipleConstraints class is used to define constraints on multiple bones, such as the minimum and maximum number of entries allowed and whether value duplicates are allowed. .. py:attribute:: min :type: int :value: 0 An integer representing the lower bound of how many entries can be submitted (default: 0). .. py:attribute:: max :type: int :value: 0 An integer representing the upper bound of how many entries can be submitted (default: 0 = unlimited). .. py:attribute:: duplicates :type: bool :value: False A boolean indicating if the same value can be used multiple times (default: False). .. py:class:: 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. .. py:attribute:: severity :type: ReadFromClientErrorSeverity A ReadFromClientErrorSeverity enumeration value representing the severity of the error. .. py:attribute:: errorMessage :type: str A string containing a human-readable error message describing the issue. .. py:attribute:: fieldPath :type: list[str] A list of strings representing the path to the field where the error occurred. .. py:attribute:: invalidatedFields :type: list[str] A list of strings containing the names of invalidated fields, if any. .. py:class:: ReadFromClientErrorSeverity Bases: :py:obj:`enum.Enum` ReadFromClientErrorSeverity is an enumeration that represents the severity levels of errors that can occur while reading data from the client. .. py:attribute:: NotSet :value: 0 No error occurred .. py:attribute:: InvalidatesOther :value: 1 The data is valid, for this bone, but in relation to other invalid .. py:attribute:: Empty :value: 2 The data is empty, but the bone requires a value .. py:attribute:: Invalid :value: 3 The data is invalid, but the bone requires a value .. py:class:: UniqueLockMethod Bases: :py:obj:`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. .. py:attribute:: SameValue :value: 1 Lock this value so that there is only one entry, or lock each value individually if the bone is multiple. .. py:attribute:: SameSet :value: 2 Lock the same set of entries (including duplicates) regardless of their order. .. py:attribute:: SameList :value: 3 Lock the same set of entries (including duplicates) in a specific order. .. py:class:: 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. .. py:attribute:: method :type: UniqueLockMethod A UniqueLockMethod enumeration value specifying how to handle multiple values for bones with multiple=True. .. py:attribute:: lockEmpty :type: 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. .. py:attribute:: message :type: str A string containing an error message displayed to the user if the requested value is already taken. .. py:class:: BooleanBone(*, defaultValue = None, **kwargs) Bases: :py:obj:`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`. :param defaultValue: The default value of the `BooleanBone` instance. Defaults to `False`. :type defaultValue: bool :raises ValueError: If the `defaultValue` is not a boolean value (`True` or `False`). Initializes a new Bone. .. py:attribute:: type :value: 'bool' .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: getEmptyValue() Returns the empty value of the `BooleanBone` class, which is `False`. :return: The empty value of the `BooleanBone` class (`False`). :rtype: bool .. py:method:: isEmpty(value) Checks if the given boolean value is empty. :param value: The boolean value to be checked. :return: `True` if the boolean value is empty (i.e., equal to the empty value of the `BooleanBone` class), `False` otherwise. :rtype: bool .. py:method:: refresh(skel, boneName) Inverse of serialize. Evaluates whats read from the datastore and populates this bone accordingly. :param name: The property-name this bone has in its Skeleton (not the description!) .. py:method:: 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. :param skel: Dictionary with the current values from the skeleton the bone belongs to :param boneName: The name of the bone that should be modified :param value: The value that should be assigned. Its type depends on the type of the bone :param append: If True, the given value will be appended to the existing bone values instead of replacing them. Only supported on bones with multiple=True :param language: Optional, the language of the value if the bone is language-aware :return: A boolean indicating whether the operation succeeded or not :rtype: bool .. py:method:: 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. .. py:method:: buildDBFilter(name, skel, dbFilter, rawFilter, prefix = None) Builds a database filter based on the boolean value. :param name: The name of the `BooleanBone` instance. :param skel: The `SkeletonInstance` object representing the data of the current entity. :param dbFilter: The `Query` object representing the current database filter. :param rawFilter: The dictionary representing the raw filter data received from the client. :param prefix: A prefix to be added to the property name in the database filter. :return: The updated `Query` object representing the updated database filter. :rtype: google.cloud.ndb.query.Query .. py:class:: CaptchaBone(*, publicKey = None, privateKey = None, score_threshold = 0.5, **kwargs) Bases: :py:obj:`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 supports v2 and v3. .. seealso:: Option :attr:`core.config.Security.captcha_default_credentials` for global security settings. Option :attr:`core.config.Security.captcha_enforce_always` for developing. Initializes a new CaptchaBone. `publicKey` and `privateKey` can be omitted, if they are set globally in :attr:`core.config.Security.captcha_default_credentials`. :param publicKey: The public key for the Captcha validation. :param privateKey: The private key for the Captcha validation. :score_threshold: If reCAPTCHA v3 is used, the score must be at least this threshold. For reCAPTCHA v2 this property will be ignored. .. py:attribute:: type :value: 'captcha' .. py:method:: serialize(skel, name, parentIndexed) Serializing the Captcha bone is not possible so it return False .. py:method:: unserialize(skel, name) Stores the publicKey in the SkeletonInstance :param skel: The target :class:`SkeletonInstance`. :param name: The name of the CaptchaBone in the :class:`SkeletonInstance`. :returns: boolean, that is true, as the Captcha bone is always unserialized successfully. .. py:method:: fromClient(skel, name, data) Load the reCAPTCHA token from the provided data and validate it with the help of the API. reCAPTCHA provides the token via callback usually as "g-recaptcha-response", but to fit into the skeleton logic, we support both names. So the token can be provided as "g-recaptcha-response" or the name of the CaptchaBone in the Skeleton. While the latter one is the preferred name. .. py:class:: ColorBone(*, mode='rgb', **kwargs) Bases: :py:obj:`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. :param type: A string representing the bone type, set to "color". :param mode: A string specifying the color mode, either "rgb" or "rgba". Default is "rgb". :param \**kwargs: Additional keyword arguments passed to the BaseBone constructor. Initializes a new Bone. .. py:attribute:: type :value: 'color' .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:class:: CredentialBone(*, max_length = None, **kwargs) Bases: :py:obj:`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 :ivar str type: The type identifier of the bone, set to "str.credential". Initializes a new StringBone. :param caseSensitive: When filtering for values in this bone, should it be case-sensitive? :param max_length: The maximum length allowed for values of this bone. Set to None for no limitation. :param min_length: The minimum length allowed for values of this bone. Set to None for no limitation. :param 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. :param kwargs: Inherited arguments from the BaseBone. .. py:attribute:: type :value: 'str.credential' .. py:method:: isInvalid(value) Returns None if the value would be valid for this bone, an error-message otherwise. .. py:method:: 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. :param skel: The skeleton instance that the bone is part of. :type skel: SkeletonInstance :param str name: The name of the bone attribute. :param bool parentIndexed: Indicates whether the parent entity is indexed. :return: True if the value was updated in the database, False otherwise. :rtype: bool .. py:method:: 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. :param dict valuesCache: A dictionary containing the serialized values from the datastore. :param str name: The name of the bone attribute. :return: An empty dictionary, as the CredentialBone's value is always empty when read from the database. :rtype: dict .. py:method:: 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. .. py:class:: DateBone(*, creationMagic = False, date = True, localize = None, naive = False, time = True, updateMagic = False, **kwargs) Bases: :py:obj:`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. :param bool creationMagic: Use the current time as value when creating an entity; ignoring this bone if the entity gets updated. :param bool updateMagic: Use the current time whenever this entity is saved. :param bool date: If True, the bone will contain date information. :param time: If True, the bone will contain time information. :param localize: 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. Initializes a new DateBone. :param creationMagic: Use the current time as value when creating an entity; ignoring this bone if the entity gets updated. :param updateMagic: Use the current time whenever this entity is saved. :param date: Should this bone contain a date-information? :param time: Should this bone contain time information? :param localize: Assume users timezone for in and output? Only valid if this bone contains date and time-information! Per default, UTC time is used. :param naive: Use naive datetime for this bone, the default is aware. .. py:attribute:: type :value: 'date' .. py:method:: 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. :param bone_name: Our name in the skeleton :param client_data: *User-supplied* request-data, has to be of valid format :returns: tuple[datetime or None, [Errors] or None] .. py:method:: 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. :param datetime value: 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. :rtype: str or None .. py:method:: 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. :rtype: pytz timezone object .. py:method:: 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. :param datetime value: The input datetime value to be serialized. :param SkeletonInstance skel: The instance of the skeleton that contains this bone. :param str name: The name of the bone in the skeleton. :param bool parentIndexed: A boolean indicating if the parent bone is indexed. :returns: The serialized datetime value with unwanted parts removed and timezone-aware. :rtype: datetime .. py:method:: 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. :param datetime value: 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. :rtype: datetime or None .. py:method:: 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. :param str name: The name of the dateBone in the skeleton. :param SkeletonInstance skel: The skeleton instance containing the dateBone. :param db.Query dbFilter: The datastore query to which the filter will be applied. :param Dict rawFilter: The raw filter dictionary containing the filter values. :param Optional[str] prefix: An optional prefix to use for the filter key, defaults to None. :returns: The datastore query with the constructed filter applied. :rtype: db.Query .. py:method:: 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. :param dict valuesCache: The cache of values to be stored in the datastore. :param str name: The name of the dateBone in the skeleton. :param bool isAdd: A flag indicating whether the operation is adding a new entry (True) or updating an existing one (False). .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: EmailBone(*, caseSensitive = True, max_length = 254, min_length = None, natural_sorting = False, **kwargs) Bases: :py:obj:`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. :param caseSensitive: When filtering for values in this bone, should it be case-sensitive? :param max_length: The maximum length allowed for values of this bone. Set to None for no limitation. :param min_length: The minimum length allowed for values of this bone. Set to None for no limitation. :param 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. :param kwargs: Inherited arguments from the BaseBone. .. py:attribute:: type :value: 'str.email' A string representing the type of the bone, in this case "str.email". .. py:method:: isInvalid(value) Checks if the provided email address is valid or not. :param str value: The email address to be validated. :returns: An error message if the email address is invalid or None if it is valid. :rtype: 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. .. py:class:: FileBone(*, derive = None, maxFileSize = None, validMimeTypes = None, refKeys = ('name', 'mimetype', 'size', 'width', 'height', 'derived'), **kwargs) Bases: :py:obj:`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. :param format: Hint for the UI how to display a file entry (defaults to it's filename) :param maxFileSize: 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. :param derive: 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. .. code-block:: python # Example derive = { "thumbnail": [{"width": 111}, {"width": 555, "height": 666}]} :param validMimeTypes: A list of Mimetypes that can be selected in this bone (or None for any) Wildcards ("image\/*") are supported. .. code-block:: python # Example validMimeTypes=["application/pdf", "image/*"] Initializes a new Filebone. All properties inherited by RelationalBone are supported. :param format: Hint for the UI how to display a file entry (defaults to it's filename) :param maxFileSize: 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. :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. .. code-block:: python # Example derive = {"thumbnail": [{"width": 111}, {"width": 555, "height": 666}]} :param validMimeTypes: A list of Mimetypes that can be selected in this bone (or None for any). Wildcards `('image\*')` are supported. .. code-block:: python #Example validMimeTypes=["application/pdf", "image/*"] .. py:attribute:: kind :value: 'file' The kind of this bone is 'file' .. py:attribute:: type :value: 'relational.tree.leaf.file' The type of this bone is 'relational.tree.leaf.file'. .. py:method:: isInvalid(value) Checks if the provided value is invalid for this bone based on its MIME type and file size. :param dict value: The value to check for validity. :returns: None if the value is valid, or an error message if it is invalid. .. py:method:: postSavedHandler(skel, boneName, key) Handles post-save processing for the FileBone, including ensuring derived files are built. :param SkeletonInstance skel: The skeleton instance this bone belongs to. :param str boneName: The name of the bone. :param db.Key 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. .. py:method:: getReferencedBlobs(skel, name) Retrieves the referenced blobs in the FileBone. :param SkeletonInstance skel: The skeleton instance this bone belongs to. :param str name: The name of the bone. :return: A set of download keys for the referenced blobs. :rtype: 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. .. py:method:: refresh(skel, boneName) Refreshes the FileBone by recreating file entries if needed and importing blobs from ViUR 2. :param SkeletonInstance skel: The skeleton instance this bone belongs to. :param str boneName: 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. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: JsonBone(*, indexed = False, multiple = False, languages = None, schema = {}, **kwargs) Bases: :py:obj:`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. .. code-block:: python # 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. .. py:attribute:: type :value: 'raw.json' .. py:method:: 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. .. py:method:: 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. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: KeyBone(*, descr = 'Key', readOnly = True, visible = False, allowed_kinds = None, check = False, **kwargs) Bases: :py:obj:`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. :param str descr: The description of the KeyBone. :param bool readOnly: Whether the KeyBone is read-only. :param bool visible: Whether the KeyBone is visible. :param Union[None, List[str]] allowed_kinds: The allowed entity kinds for the KeyBone. :param bool check: Whether to check for entity existence. Initializes a new Bone. .. py:attribute:: type :value: 'key' .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: 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. :param skel: The SkeletonValues instance this bone is a part of. :param name: The property name of this bone in the Skeleton (not the description). :return: 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. .. note:: The method contains an inner function, fixVals(val), which normalizes and validates the key values before populating the bone. .. py:method:: 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. :param skel: The SkeletonInstance this bone is a part of. :param name: The property name of this bone in the Skeleton (not the description). :param parentIndexed: A boolean value indicating whether the parent entity is indexed or not. :return: 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. .. note:: Key values are always indexed, so the method discards any exclusion from indexing for key values. .. py:method:: 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. :param name: The property name of this bone in the Skeleton (not the description). :param skel: The :class:viur.core.skeleton.SkeletonInstance this bone is a part of. :param dbFilter: The current :class:viur.core.db.Query instance the filters should be applied to. :param rawFilter: The dictionary of filters the client wants to have applied. :param prefix: An optional string to prepend to the filter key. Defaults to None. :return: The modified :class:viur.core.db.Query. The method takes the following steps: #. Decodes the provided key(s) from the raw filter. #. 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. #. If the filter contains a single key, it applies the filter directly to the query. #. In case of any invalid key or other issues, it raises a RuntimeError. .. py:class:: NumericBone(*, min = MIN, max = MAX, precision = 0, mode=None, **kwargs) Bases: :py:obj:`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. Initializes a new NumericBone. :param min: Minimum accepted value (including). :param max: Maximum accepted value (including). :param precision: How may decimal places should be saved. Zero casts the value to int instead of float. .. py:attribute:: type :value: 'numeric' .. py:method:: __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. :param key: The name of the attribute to be set. :param value: The value to set the attribute to. :raises AssertionError: If the 'multiple' attribute is set to True for a float bone. .. py:method:: isInvalid(value) This method checks if a given value is invalid (e.g., NaN) for the NumericBone instance. :param value: The value to be checked for validity. :return: Returns a string "NaN not allowed" if the value is invalid (NaN), otherwise None. .. py:method:: getEmptyValue() This method returns an empty value depending on the precision attribute of the NumericBone instance. :return: Returns 0 for integers (when precision is 0) or 0.0 for floating-point numbers (when precision is non-zero). .. py:method:: 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. :param value: The raw value to be checked for emptiness. :return: Returns True if the raw value is considered empty, otherwise False. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: 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) :param name: The property-name this bone has in its Skeleton (not the description!) :param skel: The :class:`viur.core.db.Query` this bone is part of :param dbFilter: The current :class:`viur.core.db.Query` instance the filters should be applied to :param rawFilter: The dictionary of filters the client wants to have applied :returns: The modified :class:`viur.core.db.Query` .. py:method:: 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. :param skel: The skeleton instance containing the bone. :param name: The name of the bone. :return: Returns a set of search tags as strings. .. py:method:: _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. .. py:method:: 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. .. py:method:: 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. :param skel: The skeleton instance where the values should be loaded from. This is an instance of a class derived from `viur.core.skeleton.SkeletonInstance`. :param name: 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. :return: 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. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: PasswordBone(*, descr = 'Password', test_threshold = 4, tests = tests, **kwargs) Bases: :py:obj:`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. :param test_threshold: The minimum number of tests the password must pass. :param password_tests: Defines separate tests specified as tuples of regex, hint and required-flag. .. py:attribute:: type :value: 'password' A string representing the bone type, which is "password" in this case. .. py:attribute:: saltLength :value: 13 .. py:attribute:: tests :type: Iterable[Iterable[Tuple[str, str, bool]]] :value: (('^.*[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. .. py:method:: 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. :param str value: The password to be checked. :return: True if the password is invalid, otherwise False. :rtype: bool .. py:method:: 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. :param SkeletonInstance skel: The skeleton instance to store the password in. :param str name: The name of the password field. :param dict data: The data dictionary containing the password field value. :return: None if the password is valid, otherwise a list of ReadFromClientErrors. :rtype: Union[None, List[ReadFromClientError]] .. py:method:: 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. :param SkeletonInstance skel: The skeleton instance where the password will be stored as a hashed value along with its salt. :param str name: The name of the password field used to access the password value in the data dictionary. :param dict data: The data dictionary containing the password field value, typically submitted by the client. :return: None if the password is valid and successfully stored in the skeleton instance; otherwise, a list of ReadFromClientErrors containing detailed information about the errors. :rtype: Union[None, List[ReadFromClientError]] .. py:method:: 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. :param dict skeletonValues: The dictionary containing the values from the datastore. :param str name: The name of the password field. :return: False, as no password value will be unserialized. :rtype: bool .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: RandomSliceBone(*, visible=False, readOnly=True, slices=2, sliceSize=0.5, **kwargs) Bases: :py:obj:`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. :param visible: Indicates if the bone is visible, defaults to False. :param readOnly: Indicates if the bone is read-only, defaults to True. :param slices: The number of slices to use, defaults to 2. :param sliceSize: The size of each slice, defaults to 0.5. :param kwargs: Additional keyword arguments. Initializes a new RandomSliceBone. .. py:attribute:: type :value: 'randomslice' .. py:method:: 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. :param SkeletonInstance skel: The SkeletonInstance this bone is part of. :param str name: The property name this bone has in its Skeleton (not the description). :param bool parentIndexed: Indicates if the parent bone is indexed. :return: Returns True if the serialization is successful. :rtype: bool .. py:method:: 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. :param str name: The property name this bone has in its Skeleton (not the description). :param SkeletonInstance skel: The :class:viur.core.skeleton.Skeleton instance this bone is part of. :param db.Query dbFilter: The current :class:viur.core.db.Query instance the filters should be applied to. :param Dict rawFilter: The dictionary of filters the client wants to have applied. :return: The modified :class:viur.core.db.Query instance. :rtype: 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. .. py:method:: calculateInternalMultiQueryLimit(query, targetAmount) Calculates the number of entries to be fetched in each subquery. :param db.Query query: The :class:viur.core.db.Query instance. :param int targetAmount: The number of entries to be returned from the db.Query. :return: The number of elements the db.Query should fetch on each subquery. :rtype: int .. py:method:: customMultiQueryMerge(dbFilter, result, targetAmount) Merges the results of multiple subqueries by randomly selecting 'targetAmount' elements from the combined 'result' list. :param db.Query dbFilter: The db.Query instance calling this function. :param List[db.Entity] result: The list of results for each subquery that has been run. :param int targetAmount: The number of results to be returned from the db.Query. :return: A list of elements to be returned from the db.Query. :rtype: List[db.Entity] .. py:class:: RawBone(*, compute = None, defaultValue = None, descr = '', getEmptyValueFunc = None, indexed = True, isEmptyFunc = None, languages = None, multiple = False, params = None, readOnly = None, required = False, searchable = False, type_suffix = '', unique = None, vfunc = None, visible = True) Bases: :py:obj:`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. .. py:attribute:: type :value: 'raw' .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:class:: RecordBone(*, format = None, indexed = False, using = None, **kwargs) Bases: :py:obj:`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. :param format: Optional string parameter to specify the format of the record bone. :param indexed: Optional boolean parameter to indicate if the record bone is indexed. Defaults to False. :param using: A class that inherits from 'viur.core.skeleton.RelSkel' to be used with the RecordBone. :param kwargs: Additional keyword arguments to be passed to the BaseBone constructor. Initializes a new Bone. .. py:attribute:: type :value: 'record' .. py:method:: singleValueUnserialize(val) Unserializes a single value, creating an instance of the 'using' class and unserializing the value into it. :param val: The value to unserialize. :return: An instance of the 'using' class with the unserialized data. :raises AssertionError: If the unserialized value is not a dictionary. .. py:method:: singleValueSerialize(value, skel, name, parentIndexed) Serializes a single value by calling the serialize method of the 'using' skeleton instance. :param value: The value to be serialized, which should be an instance of the 'using' skeleton. :param skel: The parent skeleton instance. :param name: The name of the bone. :param parentIndexed: A boolean indicating if the parent bone is indexed. :return: The serialized value. .. py:method:: _get_single_destinct_hash(value) Returns a distinct hash value for a single entry of this bone. The returned value must be hashable. .. py:method:: 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. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: getSearchTags(skel, name) Collects search tags from the 'using' skeleton instance for the given bone. :param skel: The parent skeleton instance. :param name: The name of the bone. :return: A set of search tags generated from the 'using' skeleton instance. .. py:method:: getSearchDocumentFields(valuesCache, name, prefix='') Generates a list of search document fields for the given values cache, name, and optional prefix. :param dict valuesCache: A dictionary containing the cached values. :param str name: The name of the bone to process. :param str prefix: An optional prefix to use for the search document fields, defaults to an empty string. :return: A list of search document fields. :rtype: list .. py:method:: getReferencedBlobs(skel, name) Retrieves a set of referenced blobs for the given skeleton instance and name. :param skel: The skeleton instance to process. :param name: The name of the bone to process. :return: A set of referenced blobs. .. py:method:: getUniquePropertyIndexValues(valuesCache, name) :abstractmethod: 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). .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: RelationalBone(*, consistency = RelationalConsistency.Ignore, format = '$(dest.name)', kind = None, module = None, parentKeys = {'name'}, refKeys = {'name'}, updateLevel = RelationalUpdateLevel.Always, using = None, **kwargs) Bases: :py:obj:`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. :param kind: KindName of the referenced property. :param module: Name of the module which should be used to select entities of kind "kind". If not set, the value of "kind" will be used (the kindName must match the moduleName) :param refKeys: 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! :param parentKeys: 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. :param 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. :param 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: - 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. :param 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 :param consistency: 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. Initialize a new RelationalBone. :param kind: KindName of the referenced property. :param 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) :param 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! :param 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. :param 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. :param 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. :param 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 :param 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. .. py:attribute:: type :value: 'relational' .. py:attribute:: kind .. py:method:: 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. :rtype: None .. py:method:: _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. :return: A tuple containing the reference skeleton and the 'using' skeleton. :rtype: tuple .. py:method:: 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. :param val: A JSON-encoded datastore property. :type val: str or dict :return: The deserialized value with restored RelSkel and Using-Skel. :rtype: dict :raises AssertionError: If the deserialized value is not a dictionary. .. py:method:: 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. :param SkeletonInstance skel: The skeleton instance containing the values to be serialized. :param str name: The name of the bone to be serialized. :param bool parentIndexed: A flag indicating whether the parent bone is indexed. :return: True if the serialization is successful, False otherwise. :rtype: bool :raises AssertionError: If a programming error is detected. .. py:method:: _get_single_destinct_hash(value) Returns a distinct hash value for a single entry of this bone. The returned value must be hashable. .. py:method:: 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. :param skel: The saved skeleton instance. :param boneName: The name of the relational bone. :param key: The key of the saved skeleton instance. .. py:method:: 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. :param skel: The deleted SkeletonInstance. :param boneName: The name of the RelationalBone in the Skeleton. :param key: The key of the deleted Entity. .. py:method:: 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. :param key: The key to be checked for validity. :return: None, as the actual validation is performed elsewhere. .. py:method:: 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. :return: True if the using-skeleton is not None and subfields should be parsed, False otherwise. :rtype: bool .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: _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. :param str name: The name of the bone. :param SkeletonInstance skel: The skeleton instance the bone is a part of. :param viur.core.db.Query dbFilter: The original datastore query to be rewritten. :param dict rawFilter: The raw filter applied to the original datastore query. :return: A tuple containing the name, skeleton, rewritten query, and raw filter. :rtype: Tuple[str, 'viur.core.skeleton.SkeletonInstance', 'viur.core.db.Query', dict] :raises NotImplementedError: If the original query contains multiple filters with "IN" or "!=" operators. :raises RuntimeError: If the filtering is invalid, e.g., using multiple key filters or querying properties not in parentKeys. .. py:method:: 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. :param str name: The name of the bone. :param SkeletonInstance skel: The skeleton instance the bone is a part of. :param db.Query dbFilter: The original datastore query to be modified. :param dict rawFilter: The raw filter applied to the original datastore query. :param str prefix: Optional prefix to be applied to filter keys. :return: The modified datastore query. :rtype: db.Query :raises RuntimeError: If the filtering is invalid, e.g., querying properties not in 'refKeys' or not a bone in 'using'. .. py:method:: 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. :param str name: The name of the bone. :param SkeletonInstance skel: The skeleton instance the bone is a part of. :param db.Query dbFilter: The original datastore query to be modified. :param dict rawFilter: The raw filter applied to the original datastore query. :return: The modified datastore query with updated sorting behavior. :rtype: t.Optional[db.Query] :raises RuntimeError: If the sorting is invalid, e.g., using properties not in 'refKeys' or not a bone in 'using'. .. py:method:: 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. :param str name: The name of the bone. :param db.Query query: The datastore query to be modified. :param str param: The filter parameter to be checked and potentially modified. :param value: The value associated with the filter parameter. :return: A tuple containing the modified filter parameter and its associated value, or None if the filter parameter is a key special property. :rtype: Tuple[str, Any] or None :raises RuntimeError: If the filtering is invalid, e.g., using properties not in 'refKeys' or 'parentKeys'. .. py:method:: 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. :param name: The name of the bone. :param query: The datastore query to be modified. :param orderings: A list or tuple of orderings to be checked and potentially modified. :type orderings: List[Union[str, Tuple[str, db.SortOrder]]] or Tuple[Union[str, Tuple[str, db.SortOrder]]] :return: A list of modified orderings that are compatible with the viur-relations index. :rtype: List[Union[str, Tuple[str, db.SortOrder]]] :raises RuntimeError: If the ordering is invalid, e.g., using properties not in 'refKeys' or 'parentKeys'. .. py:method:: 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. :param SkeletonInstance skel: The skeleton containing the bone to be refreshed. :param str boneName: The name of the bone to be refreshed. .. py:method:: 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. :param skel: The skeleton containing the bone for which search tags are to be retrieved. :param name: The name of the bone for which search tags are to be retrieved. :return: A set of search tags for the specified relational bone. .. py:method:: 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. :param Union[str, db.Key] key: The database key of the entity for which a relSkel instance is to be created. :param Union[dict, None]rel: Optional relation data to be included in the resulting dictionary. Default is None. :return: A dictionary containing a reference skeleton and optional relation data. :rtype: dict .. py:method:: 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. :param skel: Dictionary with the current values from the skeleton we belong to. :param boneName: The name of the bone to be modified. :param value: The value to be assigned. The type depends on the bone type. :param append: If true, the given value is appended to the values of the bone instead of replacing it. Only supported on bones with multiple=True. :param language: Set/append for a specific language (optional). Required if the bone supports languages. :return: True if the operation succeeded, False otherwise. .. py:method:: getReferencedBlobs(skel, name) Retrieves the set of referenced blobs from the specified bone in the given skeleton instance. :param SkeletonInstance skel: The skeleton instance to extract the referenced blobs from. :param str name: The name of the bone to retrieve the referenced blobs from. :return: A set containing the unique blob keys referenced by the specified bone. :rtype: Set[str] .. py:method:: 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`). :param dict valuesCache: The cache containing the current values of the bone. :param str name: The name of the bone for which to generate unique property index values. :return: A list containing the unique property index values for the specified bone. :rtype: List[str] .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: RelationalConsistency Bases: :py:obj:`enum.IntEnum` An enumeration representing the different consistency strategies for handling stale relations in the RelationalBone class. Initialize self. See help(type(self)) for accurate signature. .. py:attribute:: Ignore :value: 1 Ignore stale relations, which represents the old behavior. .. py:attribute:: PreventDeletion :value: 2 Lock the target object so that it cannot be deleted. .. py:attribute:: SetNull :value: 3 Drop the relation if the target object is deleted. .. py:attribute:: CascadeDeletion :value: 4 .. warning:: Delete this object also if the referenced entry is deleted (Dangerous!) .. py:class:: RelationalUpdateLevel Bases: :py:obj:`enum.Enum` An enumeration representing the different update levels for the RelationalBone class. .. py:attribute:: Always :value: 0 Always update the relational information, regardless of the context. .. py:attribute:: OnRebuildSearchIndex :value: 1 Update the relational information only when rebuilding the search index. .. py:attribute:: OnValueAssignment :value: 2 Update the relational information only when a new value is assigned to the bone. .. py:class:: SelectCountryBone(*, descr='Country', codes=ISO2, values=None, **kwargs) Bases: :py:obj:`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). :param codes: The version of the ISO-Codes, either 2 or 3 :param values: Optional, either a str representing a predefined group (currently "dach" and "eu"), a list of ISO-Codes (must match the Code-Length from `codes`), or a dict with matching iso-codes as keys and the full country-names as values. Initializes a new SelectBone. :param defaultValue: key(s) of the values which will be checked by default. :param values: dict of key->value pairs from which the user can choose from -- or a callable that returns a dict. :param 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`). :param kwargs: Additional keyword arguments that will be passed to the superclass' __init__ method. .. py:attribute:: ISO3CODES ISO 3166-1 alpha-3 (commonly referred to as ISO3) is a part of the ISO 3166 standard, which defines three-letter codes to represent countries. .. py:attribute:: ISO2CODES The ISO 2 country code (also known as ISO 3166-1 alpha-2) is an international standard consisting of two-letter codes used to identify countries. .. py:attribute:: ISO3TOISO2 A Map of ISO3 to ISO2 country codes .. py:attribute:: ISO2TOISO3 A built Map of ISO2 to ISO3 country codes .. py:attribute:: subgroup_mappings .. py:attribute:: type :value: 'select.country' .. py:attribute:: ISO2 :value: 2 .. py:attribute:: ISO3 :value: 3 .. py:method:: 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. :param val: The value to be unserialized, typically a string representing an ISO country code. :return: The unserialized value, either the original or converted ISO country code. .. py:class:: SelectBone(*, defaultValue = None, values = (), translation_key_prefix = '', **kwargs) Bases: :py:obj:`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. :param defaultValue: key(s) of the values which will be checked by default. :param values: dict of key->value pairs from which the user can choose from -- or a callable that returns a dict. :param 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`). :param kwargs: Additional keyword arguments that will be passed to the superclass' __init__ method. .. py:attribute:: type :value: 'select' .. py:method:: __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. :param str item: The attribute name. :return: The value of the specified attribute. :raises AssertionError: If the resulting values are not of type dict or OrderedDict. .. py:method:: 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. .. py:method:: 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. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:function:: translation_key_prefix_skeleton_bonename(bones_instance) Generate a translation key prefix based on the skeleton and bone name .. py:function:: translation_key_prefix_bonename(bones_instance) Generate a translation key prefix based on the bone name .. py:class:: SortIndexBone(*, defaultValue = lambda *args, **kwargs: time.time(), descr = 'SortIndex', precision = 8, **kwargs) Bases: :py:obj:`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. :param int | float defaultValue: 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. :param str descr: A short description of the bone, set to "SortIndex" by default. :param int precision: The precision of the numeric value, determining the number of decimal places allowed. The default value is 8. :param dict kwargs: Additional keyword arguments that can be passed to the parent NumericBone class. Initializes a new NumericBone. :param min: Minimum accepted value (including). :param max: Maximum accepted value (including). :param precision: How may decimal places should be saved. Zero casts the value to int instead of float. .. py:attribute:: type :value: 'numeric.sortindex' .. py:class:: SpatialBone(*, boundsLat, boundsLng, gridDimensions, **kwargs) Bases: :py:obj:`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)``` :param Tuple[float, float] boundsLat: The outer bounds (Latitude) of the region we will search in :param Tuple[float, float] boundsLng: The outer bounds (Longitude) of the region we will search in :param gridDimensions: (Tuple[int, int]) The number of sub-regions the map will be divided in Initializes a new SpatialBone. :param boundsLat: Outer bounds (Latitude) of the region we will search in. :param boundsLng: Outer bounds (Longitude) of the region we will search in. :param gridDimensions: Number of sub-regions the map will be divided in .. py:attribute:: type :value: 'spatial' .. py:method:: getGridSize() Calculate and return the size of the sub-regions in terms of fractions of latitude and longitude. :return: A tuple containing the size of the sub-regions as (fractions-of-latitude, fractions-of-longitude) :rtype: (float, float) .. py:method:: isInvalid(value) Validate if the given point (latitude, longitude) falls within the specified boundaries. Rejects all values outside the defined region. :param value: A tuple containing the location of the entry as (latitude, longitude) :return: An error description if the value is invalid or False if the value is valid :rtype: str | bool .. py:method:: 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. :param value: A tuple containing the location of the entry as (latitude, longitude) :param SkeletonInstance skel: The instance of the Skeleton this bone is attached to :param str name: The name of this bone :param bool parentIndexed: A boolean indicating if the parent bone is indexed :return: A dictionary containing the serialized data, including coordinates and tile information (if indexed) :rtype: dict | None .. py:method:: singleValueUnserialize(val) Deserialize a single value (latitude, longitude) from the stored data. :param val: A dictionary containing the serialized data, including coordinates :return: A tuple containing the location of the entry as (latitude, longitude) :rtype: Tuple[float, float] | None .. py:method:: parseSubfieldsFromClient() Determines if subfields (latitude and longitude) should be parsed from the client. :return: Always returns True, as latitude and longitude are required :rtype: bool .. py:method:: isEmpty(value) Check if the given raw value is considered empty (either not present or equal to the empty value). :param value: The raw value to be checked :return: True if the raw value is considered empty, False otherwise :rtype: bool .. py:method:: 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. :return: A tuple representing an empty value for this bone (91.0, 181.0) :rtype: Tuple[float, float] .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: 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. :param str name: The property name this bone has in its Skeleton (not the description!) :param SkeletonInstance skel: The skeleton this bone is part of :param db.Query dbFilter: The current `viur.core.db.Query` instance to which the filters should be applied :param dict rawFilter: The dictionary of filters the client wants to have applied :param prefix: Optional string, specifying a prefix for the bone's name (default is None) :return: The modified `viur.core.db.Query` instance :rtype: db.Query .. py:method:: calculateInternalMultiQueryLimit(dbQuery, targetAmount) Provides guidance to viur.core.db.Query on the number of entries that should be fetched in each subquery. :param dbQuery: The `viur.core.db.Query` instance :param targetAmount: The desired number of entries to be returned from the db.Query :return: The number of elements db.Query should fetch for each subquery :rtype: int .. py:method:: customMultiQueryMerge(name, lat, lng, dbFilter, result, targetAmount) Randomly returns 'targetAmount' elements from 'result'. :param str name: The property-name this bone has in its Skeleton (not the description!) :param lat: Latitude of the reference point :param lng: Longitude of the reference point :param dbFilter: The db.Query instance calling this function :param result: The list of results for each subquery that was executed :param int targetAmount: The desired number of results to be returned from db.Query :return: List of elements to be returned from db.Query :rtype: List[db.Entity] .. py:method:: 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. :param skel: Dictionary with the current values from the skeleton the bone belongs to :param boneName: The name of the bone that should be modified :param value: The value that should be assigned. Its type depends on the type of the bone :param append: If True, the given value will be appended to the existing bone values instead of replacing them. Only supported on bones with multiple=True :param language: Optional, the language of the value if the bone is language-aware :return: A boolean indicating whether the operation succeeded or not :rtype: bool .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: StringBone(*, caseSensitive = True, max_length = 254, min_length = None, natural_sorting = False, **kwargs) Bases: :py:obj:`viur.core.bones.base.BaseBone` The "StringBone" represents a data field that contains text values. Initializes a new StringBone. :param caseSensitive: When filtering for values in this bone, should it be case-sensitive? :param max_length: The maximum length allowed for values of this bone. Set to None for no limitation. :param min_length: The minimum length allowed for values of this bone. Set to None for no limitation. :param 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. :param kwargs: Inherited arguments from the BaseBone. .. py:attribute:: type :value: 'str' .. py:method:: 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). .. py:method:: singleValueSerialize(value, skel, name, parentIndexed) Serializes a single value of this data field for storage in the database. :param value: The value to serialize. It should be a str value, if not it is forced with :meth:`type_coerce_single_value`. :param skel: The skeleton instance that this data field belongs to. :param name: The name of this data field. :param parentIndexed: A boolean value indicating whether the parent object has an index on this data field or not. :return: The serialized value. .. py:method:: singleValueUnserialize(value) Unserializes a single value of this data field from the database. :param value: The serialized value to unserialize. :return: The unserialized value. .. py:method:: getEmptyValue() Returns the empty value for this data field. :return: An empty string. .. py:method:: isEmpty(value) Determines whether a value for this data field is empty or not. :param value: The value to check for emptiness. :return: A boolean value indicating whether the value is empty or not. .. py:method:: isInvalid(value) Returns None if the value would be valid for this bone, an error-message otherwise. .. py:method:: 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. .. py:method:: buildDBFilter(name, skel, dbFilter, rawFilter, prefix = None) Builds and returns a database filter for this data field based on the provided raw filter data. :param name: The name of this data field. :param skel: The skeleton instance that this data field belongs to. :param dbFilter: The database filter to add query clauses to. :param rawFilter: A dictionary containing the raw filter data for this data field. :param prefix: An optional prefix to add to the query clause. :return: The database filter with the added query clauses. .. py:method:: buildDBSort(name, skel, dbFilter, rawFilter) Build a DB sort based on the specified name and a raw filter. :param name: The name of the attribute to sort by. :param skel: A SkeletonInstance object. :param dbFilter: A Query object representing the current DB filter. :param rawFilter: A dictionary containing the raw filter. :return: The Query object with the specified sort applied. .. py:method:: natural_sorting(value) Implements a default natural sorting transformer. The sorting is according to DIN 5007 Variant 2 and sets รถ and oe, etc. equal. .. py:method:: getSearchTags(skel, name) Returns a set of lowercased words that represent searchable tags for the given bone. :param skel: The skeleton instance being searched. :param name: The name of the bone to generate tags for. :return: A set of lowercased words representing searchable tags. .. py:method:: getUniquePropertyIndexValues(skel, name) Returns a list of unique index values for a given property name. :param skel: The skeleton instance. :param name: The name of the property. :return: 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. .. py:method:: refresh(skel, bone_name) Refresh all values we might have cached from other entities. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: TextBone(*, validHtml = __undefinedC__, max_length = 200000, srcSet = None, indexed = False, **kwargs) Bases: :py:obj:`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. :param Union[None, Dict] validHtml: A dictionary containing allowed HTML tags and their attributes. Defaults to _defaultTags. Must be a structured like :prop:_defaultTags :param int max_length: The maximum allowed length for the content. Defaults to 200000. :param languages: If set, this bone can store a different content for each language :param Dict[str, List] srcSet: 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]} :param bool indexed: Whether the content should be indexed for searching. Defaults to False. :param kwargs: Additional keyword arguments to be passed to the base class constructor. :param validHtml: If set, must be a structure like :prop:_defaultTags :param languages: If set, this bone can store a different content for each language :param max_length: Limit content to max_length bytes :param indexed: Must not be set True, unless you limit max_length accordingly :param 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]} .. py:class:: __undefinedC__ .. py:attribute:: type :value: 'text' .. py:method:: 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. .. py:method:: singleValueFromClient(value, skel, bone_name, client_data) Load a single value from a client :param value: The single value which should be loaded. :param skel: The SkeletonInstance where the value should be loaded into. :param bone_name: The bone name of this bone in the SkeletonInstance. :param client_data: The data taken from the client, a dictionary with usually bone names as key :return: 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*. .. py:method:: 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 .. py:method:: 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). :param value: The value to be checked for validity. :return: Returns None if the value is valid, or an error message string otherwise. :rtype: Optional[str] .. py:method:: 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. :param SkeletonInstance skel: A SkeletonInstance object containing the data of an entry. :param str name: The name of the TextBone for which to find referenced blobs. :return: A set containing the blob keys of the referenced files in the TextBone's HTML content. :rtype: Set[str] .. py:method:: 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. :param SkeletonInstance skel: A SkeletonInstance object containing the data of an entry. :param str boneName: The name of the TextBone for which to refresh the src-set. .. py:method:: 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. :param skel: A SkeletonInstance containing the TextBone. :param name: The name of the TextBone in the skeleton. :return: A set of unique search tags (lowercase words) extracted from the text content of the TextBone. .. py:method:: 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. :param valuesCache: A dictionary containing the cached values for the TextBone. :param name: The name of the TextBone. :return: A list of unique property index values for the TextBone. :raises NotImplementedError: If the TextBone supports multiple languages. .. py:method:: structure() Describes the bone and its settings as an JSON-serializable dict. This function has to be implemented for subsequent, specialized bone types. .. py:class:: TreeLeafBone(**kwargs) Bases: :py:obj:`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. :param kind: KindName of the referenced property. :param 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) :param 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! :param 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. :param 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. :param 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. :param 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 :param 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. .. py:attribute:: type :value: 'relational.tree.leaf' .. py:class:: TreeNodeBone(*, consistency = RelationalConsistency.Ignore, format = '$(dest.name)', kind = None, module = None, parentKeys = {'name'}, refKeys = {'name'}, updateLevel = RelationalUpdateLevel.Always, using = None, **kwargs) Bases: :py:obj:`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. :param kind: KindName of the referenced property. :param 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) :param 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! :param 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. :param 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. :param 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. :param 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 :param 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. .. py:attribute:: type :value: 'relational.tree.node' .. py:class:: 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: :py:obj:`viur.core.bones.relational.RelationalBone` A specialized relational bone for handling user references. Extends the functionality of :class:`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. :param creationMagic: If True, the bone will automatically store the creating user when a new entry is added. :param updateMagic: If True, the bone will automatically store the last user who updated the entry. :raises ValueError: If the bone is multiple=True and creation/update magic is set. .. py:method:: 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. :param SkeletonInstance skel: The skeleton instance to operate on. :param str key: The key of the bone in the skeleton. :param bool isAdd: If True, the operation is an addition. Otherwise, it is an update. :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :return: True if the magic operation was successful, False otherwise. :rtype: bool