core.skeleton

Module Contents

Classes

MetaBaseSkel

This is the metaclass for Skeletons.

SkeletonInstance

The actual wrapper around a Skeleton-Class. An object of this class is what's actually returned when you

BaseSkeleton

This is a container-object holding information about one database entity.

MetaSkel

This is the metaclass for Skeletons.

DatabaseAdapter

Adapter class used to bind or use other databases and hook operations when working with a Skeleton.

ViurTagsSearchAdapter

This Adapter implements a simple fulltext search on top of the datastore.

SeoKeyBone

Special kind of StringBone saving its contents as viurCurrentSeoKeys into the entity's viur dict.

Skeleton

This is a container-object holding information about one database entity.

RelSkel

This is a Skeleton-like class that acts as a container for Skeletons used as a

RefSkel

This is a Skeleton-like class that acts as a container for Skeletons used as a

SkelList

This class is used to hold multiple skeletons together with other, commonly used information.

TaskUpdateSearchIndex

This tasks loads and saves every entity of the given module.

RebuildSearchIndex

BaseClass to run a database Query and process each entry matched.

TaskVacuumRelations

Checks entries in viur-relations and verifies that the src-kind

Functions

skeletonByKind(kindName)

Returns the Skeleton-Class for the given kindName. That skeleton must exist, otherwise an exception is raised.

listKnownSkeletons()

return:

A list of all known kindnames (all kindnames for which a skeleton is defined)

iterAllSkelClasses()

return:

An iterator that yields each Skeleton-Class once. (Only top-level skeletons are returned, so no

processRemovedRelations(removedKey[, cursor])

updateRelations(destKey, minChangeTime, changedBone[, ...])

This function updates Entities, which may have a copy of values from another entity which has been recently

processVacuumRelationsChunk(module, cursor[, ...])

Processes 25 Entries and calls the next batch

__getattr__(attr)

Attributes

_UNDEFINED

ABSTRACT_SKEL_CLS_SUFFIX

KeyType

__DEPRECATED_NAMES

core.skeleton._UNDEFINED
core.skeleton.ABSTRACT_SKEL_CLS_SUFFIX = 'AbstractSkel'
core.skeleton.KeyType: TypeAlias
class core.skeleton.MetaBaseSkel(name, bases, dct, **kwargs)

Bases: type

This is the metaclass for Skeletons. It is used to enforce several restrictions on bone names, etc.

_skelCache
_allSkelClasses
__reserved_keywords
__allowed_chars
static generate_bonemap(cls)

Recursively constructs a dict of bones from

__setattr__(key, value)

Implement setattr(self, name, value).

class core.skeleton.SkeletonInstance(skel_cls, *, bones=(), bone_map=None, clone=False, clonedBoneMap=None)

The actual wrapper around a Skeleton-Class. An object of this class is what’s actually returned when you call a Skeleton-Class. With ViUR3, you don’t get an instance of a Skeleton-Class any more - it’s always this class. This is much faster as this is a small class.

Creates a new SkeletonInstance based on skel_cls.

Parameters:
  • skel_cls (Type[Skeleton]) – Is the base skeleton class to inherit from and reference to.

  • bones (Iterable[str]) – If given, defines an iterable of bones that are take into the SkeletonInstance. The order of the bones defines the order in the SkeletonInstance.

  • bone_map (Optional[Dict[str, viur.core.bones.BaseBone]]) – A pre-defined bone map to use, or extend.

  • clone (bool) – If set True, performs a cloning of the used bone map, to be entirely stand-alone.

  • clonedBoneMap (Optional[Dict[str, viur.core.bones.BaseBone]]) –

__slots__
items(yieldBoneValues=False)
Parameters:

yieldBoneValues (bool) –

Return type:

Iterable[tuple[str, viur.core.bones.BaseBone]]

keys()
Return type:

Iterable[str]

values()
Return type:

Iterable[Any]

__iter__()
Return type:

Iterable[str]

__contains__(item)
get(item, default=None)
update(*args, **kwargs)
Return type:

None

__setitem__(key, value)
__getitem__(key)
__getattr__(item)

Get a special attribute from the SkeletonInstance

__getattr__ is called when an attribute access fails with an AttributeError. So we know that this is not a real attribute of the SkeletonInstance. But there are still a few special cases in which attributes are loaded from the skeleton class.

Parameters:

item (str) –

__delattr__(item)

Implement delattr(self, name).

__setattr__(key, value)

Implement setattr(self, name, value).

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

__len__()
Return type:

int

__ior__(other)
Parameters:

other (dict | SkeletonInstance | viur.core.db.Entity) –

Return type:

SkeletonInstance

clone()

Clones a SkeletonInstance into a modificable, stand-alone instance. This will also allow to modify the underlying data model.

ensure_is_cloned()

Ensured this SkeletonInstance is a stand-alone clone, which can be modified. Does nothing in case it was already cloned before.

setEntity(entity)
Parameters:

entity (viur.core.db.Entity) –

structure()
Return type:

dict

__deepcopy__(memodict)
class core.skeleton.BaseSkeleton

Bases: object

This is a container-object holding information about one database entity.

It has to be sub-classed with individual information about the kindName of the entities and its specific data attributes, the so called bones. The Skeleton stores its bones in an OrderedDict-Instance, so the definition order of the contained bones remains constant.

Variables:
  • key (server.bones.BaseBone) – This bone stores the current database key of this entity. Assigning to this bones value is dangerous and does not affect the actual key its stored in.

  • creationdate (server.bones.DateBone) – The date and time where this entity has been created.

  • changedate (server.bones.DateBone) – The date and time of the last change to this entity.

__viurBaseSkeletonMarker__ = True
boneMap
classmethod subSkel(*subskel_names, fullClone=False, **kwargs)
Parameters:

fullClone (bool) –

Return type:

SkeletonInstance

classmethod subskel(*names, bones=(), clone=False)

Creates a new sub-skeleton from the current skeleton.

A sub-skeleton is a copy of the original skeleton, containing only a subset of its bones.

Sub-skeletons can either be defined using the the subSkels property of the Skeleton object, or freely by giving patterns for bone names which shall be part of the sub-skeleton.

  1. Giving names as parameter merges the bones of all Skeleton.subSkels-configurations together. This is the usual behavior. By passing multiple sub-skeleton names to this function, a sub-skeleton with the union of all bones of the specified sub-skeletons is returned. If an entry called “*” exists in the subSkels-dictionary, the bones listed in this entry will always be part of the generated sub-skeleton.

  2. Given the bones parameter allows to freely specify a sub-skeleton; One specialty here is, that the order of the bones can also be changed in this mode. This mode is the new way of defining sub-skeletons, and might become the primary way to define sub-skeletons in future.

  3. Both modes (1 + 2) can be combined, but then the original order of the bones is kept.

  4. The “key” bone is automatically available in each sub-skeleton.

  5. An fnmatch-compatible wildcard pattern is allowed both in the subSkels-bone-list and the free bone list.

Example (TodoSkel is the example skeleton from viur-base): ```py # legacy mode (see 1) subskel = TodoSkel.subskel(“add”) # creates subskel: key, firstname, lastname, subject

# free mode (see 2) allows to specify a different order! subskel = TodoSkel.subskel(bones=(“subject”, “message”, “*stname”)) # creates subskel: key, subject, message, firstname, lastname

# mixed mode (see 3) subskel = TodoSkel.subskel(“add”, bones=(“message”, )) # creates subskel: key, firstname, lastname, subject, message ```

Parameters:
  • bones (Iterable[str]) – Allows to specify an iterator of bone names (more precisely, fnmatch-wildards) which allow to freely define a subskel. If only this parameter is given, the order of the specification also defines, the order of the list. Otherwise, the original order as defined in the skeleton is kept.

  • clone (bool) – If set True, performs a cloning of the used bone map, to be entirely stand-alone.

  • names (str) –

Returns:

The sub-skeleton of the specified type.

Return type:

SkeletonInstance

classmethod setSystemInitialized()
classmethod setBoneValue(skel, boneName, value, append=False, language=None)

Allows for setting a bones value without calling fromClient or assigning a value directly. Sanity-Checks are performed; if the value is invalid, that bone flips back to its original (default) value and false is returned.

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

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

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

  • language (Optional[str]) – Language to set

  • skel (SkeletonInstance) –

Returns:

Wherever that operation succeeded or not.

Return type:

bool

classmethod fromClient(skel, data, *, amend=False, ignore=None)

Load supplied data into Skeleton.

This function works similar to setValues(), except that the values retrieved from data are checked against the bones and their validity checks.

Even if this function returns False, all bones are guaranteed to be in a valid state. The ones which have been read correctly are set to their valid values; Bones with invalid values are set back to a safe default (None in most cases). So its possible to call write() afterwards even if reading data with this function failed (through this might violates the assumed consistency-model).

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

  • data (dict[str, list[str] | str]) – Dictionary from which the data is read.

  • amend (bool) – Defines whether content of data may be incomplete to amend the skel, which is useful for edit-actions.

  • ignore (Optional[Iterable[str]]) – optional list of bones to be ignored; Defaults to all readonly-bones when set to None.

Returns:

True if all data was successfully read and complete. False otherwise (e.g. some required fields where missing or where invalid).

Return type:

bool

classmethod refresh(skel)

Refresh the bones current content.

This function causes a refresh of all relational bones and their associated information.

Parameters:

skel (SkeletonInstance) –

class core.skeleton.MetaSkel(name, bases, dct, **kwargs)

Bases: MetaBaseSkel

This is the metaclass for Skeletons. It is used to enforce several restrictions on bone names, etc.

class core.skeleton.DatabaseAdapter

Adapter class used to bind or use other databases and hook operations when working with a Skeleton.

providesFulltextSearch: bool = False

Set to True if we can run a fulltext search using this database.

fulltextSearchGuaranteesQueryConstrains = False

Are results returned by meth:fulltextSearch guaranteed to also match the databaseQuery

providesCustomQueries: bool = False

Indicate that we can run more types of queries than originally supported by datastore

prewrite(skel, is_add, change_list=())

Hook being called on a add, edit or delete operation before the skeleton-specific action is performed.

The hook can be used to modifiy the skeleton before writing. The raw entity can be obainted using skel.dbEntity.

Parameters:
  • action – Either contains “add”, “edit” or “delete”, depending on the operation.

  • skel (SkeletonInstance) – is the skeleton that is being read before written.

  • change_list (Iterable[str]) – is a list of bone names which are being changed within the write.

  • is_add (bool) –

write(skel, is_add, change_list=())

Hook being called on a write operations after the skeleton is written.

The raw entity can be obainted using skel.dbEntity.

Parameters:
  • action – Either contains “add” or “edit”, depending on the operation.

  • skel (SkeletonInstance) – is the skeleton that is being read before written.

  • change_list (Iterable[str]) – is a list of bone names which are being changed within the write.

  • is_add (bool) –

delete(skel)

Hook being called on a delete operation after the skeleton is deleted.

Parameters:

skel (SkeletonInstance) –

abstract fulltextSearch(queryString, databaseQuery)

If this database supports fulltext searches, this method has to implement them. If it’s a plain fulltext search engine, leave ‘prop:fulltextSearchGuaranteesQueryConstrains’ set to False, then the server will post-process the list of entries returned from this function and drop any entry that cannot be returned due to other constrains set in ‘param:databaseQuery’. If you can obey every constrain set in that Query, we can skip this post-processing and save some CPU-cycles. :param queryString: the string as received from the user (no quotation or other safety checks applied!) :param databaseQuery: The query containing any constrains that returned entries must also match :return:

Parameters:
  • queryString (str) –

  • databaseQuery (viur.core.db.Query) –

Return type:

list[viur.core.db.Entity]

class core.skeleton.ViurTagsSearchAdapter(min_length=2, max_length=50, substring_matching=False)

Bases: DatabaseAdapter

This Adapter implements a simple fulltext search on top of the datastore.

On skel.write(), all words from String-/TextBones are collected with all min_length postfixes and dumped into the property viurTags. When queried, we’ll run a prefix-match against this property - thus returning entities with either an exact match or a match within a word.

Example:

For the word “hello” we’ll write “hello”, “ello” and “llo” into viurTags. When queried with “hello” we’ll have an exact match. When queried with “hel” we’ll match the prefix for “hello” When queried with “ell” we’ll prefix-match “ello” - this is only enabled when substring_matching is True.

We’ll automatically add this adapter if a skeleton has no other database adapter defined.

Parameters:
  • min_length (int) –

  • max_length (int) –

  • substring_matching (bool) –

providesFulltextSearch = True
fulltextSearchGuaranteesQueryConstrains = True
_tags_from_str(value)

Extract all words including all min_length postfixes from given string

Parameters:

value (str) –

Return type:

set[str]

prewrite(skel, *args, **kwargs)

Collect searchTags from skeleton and build viurTags

Parameters:

skel (SkeletonInstance) –

fulltextSearch(queryString, databaseQuery)

Run a fulltext search

Parameters:
  • queryString (str) –

  • databaseQuery (viur.core.db.Query) –

Return type:

list[viur.core.db.Entity]

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

Bases: viur.core.bones.StringBone

Special kind of StringBone saving its contents as viurCurrentSeoKeys into the entity’s viur dict.

Initializes a new StringBone.

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

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

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

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

  • kwargs – Inherited arguments from the BaseBone.

unserialize(skel, name)

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

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

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

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

Returns:

True if deserialization is successful, False otherwise.

Return type:

bool

serialize(skel, name, parentIndexed)

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

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

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

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

Returns:

A boolean indicating whether the serialization was successful.

Return type:

bool

class core.skeleton.Skeleton(*args, **kwargs)

Bases: BaseSkeleton

This is a container-object holding information about one database entity.

It has to be sub-classed with individual information about the kindName of the entities and its specific data attributes, the so called bones. The Skeleton stores its bones in an OrderedDict-Instance, so the definition order of the contained bones remains constant.

Variables:
  • key (server.bones.BaseBone) – This bone stores the current database key of this entity. Assigning to this bones value is dangerous and does not affect the actual key its stored in.

  • creationdate (server.bones.DateBone) – The date and time where this entity has been created.

  • changedate (server.bones.DateBone) – The date and time of the last change to this entity.

kindName: str

Specifies the entity kind name this Skeleton is associated with. Will be determined automatically when not explicitly set.

database_adapters: DatabaseAdapter | Iterable[DatabaseAdapter] | None

Custom database adapters. Allows to hook special functionalities that during skeleton modifications.

subSkels
interBoneValidations: list[Callable[[Skeleton], list[viur.core.bones.base.ReadFromClientError]]] = []
__seo_key_trans
key
name
creationdate
changedate
viurCurrentSeoKeys
__repr__()

Return repr(self).

__str__()

Return str(self).

classmethod all(skel, **kwargs)

Create a query with the current Skeletons kindName.

Returns:

A db.Query object which allows for entity filtering and sorting.

Return type:

viur.core.db.Query

classmethod fromClient(skel, data, *, amend=False, ignore=None)

This function works similar to setValues(), except that the values retrieved from data are checked against the bones and their validity checks.

Even if this function returns False, all bones are guaranteed to be in a valid state. The ones which have been read correctly are set to their valid values; Bones with invalid values are set back to a safe default (None in most cases). So its possible to call write() afterwards even if reading data with this function failed (through this might violates the assumed consistency-model).

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

  • data (dict[str, list[str] | str]) – Dictionary from which the data is read.

  • amend (bool) – Defines whether content of data may be incomplete to amend the skel, which is useful for edit-actions.

  • ignore (Optional[Iterable[str]]) – optional list of bones to be ignored; Defaults to all readonly-bones when set to None.

Returns:

True if all data was successfully read and complete. False otherwise (e.g. some required fields where missing or where invalid).

Return type:

bool

classmethod fromDB(skel, key)

Deprecated function, replaced by Skeleton.read().

Parameters:
Return type:

bool

classmethod read(skel, key=None, *, create=False, _check_legacy=True)

Read Skeleton with key from the datastore into the Skeleton. If not key is given, skel[“key”] will be used.

Reads all available data of entity kind kindName and the key key from the Datastore into the Skeleton structure’s bones. Any previous data of the bones will discard.

To store a Skeleton object to the Datastore, see write().

Parameters:
  • key (Optional[KeyType]) – A viur.core.db.Key, string, or int; from which the data shall be fetched. If not provided, skel[“key”] will be used.

  • create (bool | dict | Callable[[SkeletonInstance], None]) – Allows to specify a dict or initial callable that is executed in case the Skeleton with the given key does not exist, it will be created.

  • skel (SkeletonInstance) –

  • _check_legacy (bool) –

Returns:

None on error, or the given SkeletonInstance on success.

Return type:

Optional[SkeletonInstance]

classmethod toDB(skel, update_relations=True, **kwargs)

Deprecated function, replaced by Skeleton.write().

Parameters:
Return type:

viur.core.db.Key

classmethod write(skel, key=None, *, update_relations=True, _check_legacy=True)

Write current Skeleton to the datastore.

Stores the current data of this instance into the database. If an key value is set to the object, this entity will ne updated; Otherwise a new entity will be created.

To read a Skeleton object from the data store, see read().

Parameters:
  • key (Optional[KeyType]) – Allows to specify a key that is set to the skeleton and used for writing.

  • update_relations (bool) – If False, this entity won’t be marked dirty; This avoids from being fetched by the background task updating relations.

  • skel (SkeletonInstance) –

  • _check_legacy (bool) –

Returns:

The Skeleton.

Return type:

SkeletonInstance

classmethod delete(skel, key=None)

Deletes the entity associated with the current Skeleton from the data store.

Parameters:
  • key (Optional[KeyType]) – Allows to specify a key that is used for deletion, otherwise skel[“key”] will be used.

  • skel (SkeletonInstance) –

Return type:

None

classmethod patch(skel, values={}, *, key=None, check=None, create=None, update_relations=True, ignore=(), retry=0)

Performs an edit operation on a Skeleton within a transaction.

The transaction performs a read, sets bones and afterwards does a write with exclusive access on the given Skeleton and its underlying database entity.

All value-dicts that are being fed to this function are provided to skel.fromClient(). Instead of dicts, a callable can also be given that can individually modify the Skeleton that is edited.

Parameters:
  • values (Optional[dict | Callable[[SkeletonInstance], None]]) –

    A dict of key-values to update on the entry, or a callable that is executed within the transaction.

    This dict allows for a special notation: Keys starting with “+” or “-” are added or substracted to the given value, which can be used for counters.

  • key (Optional[viur.core.db.Key | int | str]) – A viur.core.db.Key, string, or int; from which the data shall be fetched. If not provided, skel[“key”] will be used.

  • check (Optional[dict | Callable[[SkeletonInstance], None]]) – An optional dict of key-values or a callable to check on the Skeleton before updating. If something fails within this check, an AssertionError is being raised.

  • create (Optional[bool | dict | Callable[[SkeletonInstance], None]]) – Allows to specify a dict or initial callable that is executed in case the Skeleton with the given key does not exist.

  • update_relations (bool) – Trigger update relations task on success. Defaults to False.

  • trust – Use internal fromClient with trusted data (may change readonly-bones)

  • retry (int) – On ViurDatastoreError, retry for this amount of times.

  • skel (SkeletonInstance) –

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

Return type:

SkeletonInstance

If the function does not raise an Exception, all went well. The function always returns the input Skeleton.

Raises:

ValueError: In case parameters where given wrong or incomplete. AssertionError: In case an asserted check parameter did not match. ReadFromClientException: In case a skel.fromClient() failed with a high severity.

classmethod preProcessBlobLocks(skel, locks)

Can be overridden to modify the list of blobs referenced by this skeleton

Parameters:

skel (SkeletonInstance) –

classmethod preProcessSerializedData(skel, entity)

Can be overridden to modify the viur.core.db.Entity before its actually written to the data store.

Parameters:

skel (SkeletonInstance) –

classmethod postSavedHandler(skel, key, dbObj)

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

Parameters:

skel (SkeletonInstance) –

classmethod postDeletedHandler(skel, key)

Can be overridden to perform further actions after the entity has been deleted from the data store.

Parameters:

skel (SkeletonInstance) –

classmethod getCurrentSEOKeys(skel)

Should be overridden to return a dictionary of language -> SEO-Friendly key this entry should be reachable under. How theses names are derived are entirely up to the application. If the name is already in use for this module, the server will automatically append some random string to make it unique. :return:

Parameters:

skel (SkeletonInstance) –

Return type:

None | dict[str, str]

class core.skeleton.RelSkel

Bases: BaseSkeleton

This is a Skeleton-like class that acts as a container for Skeletons used as a additional information data skeleton for extendedRelationalBone.

It needs to be sub-classed where information about the kindName and its attributes (bones) are specified.

The Skeleton stores its bones in an OrderedDict-Instance, so the definition order of the contained bones remains constant.

serialize(parentIndexed)
unserialize(values)

Loads ‘values’ into this skeleton.

Parameters:

values (viur.core.db.Entity | dict) – dict with values we’ll assign to our bones

class core.skeleton.RefSkel

Bases: RelSkel

This is a Skeleton-like class that acts as a container for Skeletons used as a additional information data skeleton for extendedRelationalBone.

It needs to be sub-classed where information about the kindName and its attributes (bones) are specified.

The Skeleton stores its bones in an OrderedDict-Instance, so the definition order of the contained bones remains constant.

classmethod fromSkel(kindName, *args)

Creates a relSkel from a skeleton-class using only the bones explicitly named in *args

Parameters:
  • args (list[str]) – List of bone names we’ll adapt

  • kindName (str) –

Returns:

A new instance of RefSkel

Return type:

Type[RefSkel]

read(key=None)

Read full skeleton instance referenced by the RefSkel from the database.

Can be used for reading the full Skeleton from a RefSkel. The key parameter also allows to read another, given key from the related kind.

Raises:

ValueError – If the entry is no longer in the database.

Parameters:

key (Optional[viur.core.db.Key | str | int]) –

Return type:

SkeletonInstance

class core.skeleton.SkelList(baseSkel=None)

Bases: list

This class is used to hold multiple skeletons together with other, commonly used information.

SkelLists are returned by Skel().all()…fetch()-constructs and provide additional information about the data base query, for fetching additional entries.

Variables:

cursor (str) – Holds the cursor within a query.

Parameters:

baseSkel – The baseclass for all entries in this list

__slots__ = ('baseSkel', 'customQueryInfo', 'getCursor', 'get_orders', 'renderPreparation')
core.skeleton.skeletonByKind(kindName)

Returns the Skeleton-Class for the given kindName. That skeleton must exist, otherwise an exception is raised. :param kindName: The kindname to retreive the skeleton for :return: The skeleton-class for that kind

Parameters:

kindName (str) –

Return type:

Type[Skeleton]

core.skeleton.listKnownSkeletons()
Returns:

A list of all known kindnames (all kindnames for which a skeleton is defined)

Return type:

list[str]

core.skeleton.iterAllSkelClasses()
Returns:

An iterator that yields each Skeleton-Class once. (Only top-level skeletons are returned, so no RefSkel classes will be included)

Return type:

Iterable[Skeleton]

core.skeleton.processRemovedRelations(removedKey, cursor=None)
core.skeleton.updateRelations(destKey, minChangeTime, changedBone, cursor=None)

This function updates Entities, which may have a copy of values from another entity which has been recently edited (updated). In ViUR, relations are implemented by copying the values from the referenced entity into the entity that’s referencing them. This allows ViUR to run queries over properties of referenced entities and prevents additional db.Get’s to these referenced entities if the main entity is read. However, this forces us to track changes made to entities as we might have to update these mirrored values. This is the deferred call from meth:viur.core.skeleton.Skeleton.write() after an update (edit) on one Entity to do exactly that.

Parameters:
  • destKey (viur.core.db.Key) – The database-key of the entity that has been edited

  • minChangeTime (int) – The timestamp on which the edit occurred. As we run deferred, and the entity might have been edited multiple times before we get acutally called, we can ignore entities that have been updated in the meantime as they’re already up2date

  • changedBone (Optional[str]) – If set, we’ll update only entites that have a copy of that bone. Relations mirror only key and name by default, so we don’t have to update these if only another bone has been changed.

  • cursor (Optional[str]) – The database cursor for the current request as we only process five entities at once and then defer again.

class core.skeleton.TaskUpdateSearchIndex

Bases: viur.core.tasks.CallableTaskBase

This tasks loads and saves every entity of the given module. This ensures an updated searchIndex and verifies consistency of this data.

key = 'rebuildSearchIndex'
name = 'Rebuild search index'
descr = 'This task can be called to update search indexes and relational information.'
canCall()

Checks wherever the current user can execute this task

Return type:

bool

dataSkel()

If additional data is needed, return a skeleton-instance here. These values are then passed to execute.

execute(module, *args, **kwargs)

The actual code that should be run goes here.

static _run(module, notify)
Parameters:
  • module (str) –

  • notify (str) –

class core.skeleton.RebuildSearchIndex

Bases: viur.core.tasks.QueryIter

BaseClass to run a database Query and process each entry matched. This will run each step deferred, so it is possible to process an arbitrary number of entries without being limited by time or memory.

To use this class create a subclass, override the classmethods handleEntry and handleFinish and then call startIterOnQuery with an instance of a database Query (and possible some custom data to pass along)

classmethod handleEntry(skel, customData)

Overridable hook to process one entry. “entry” will be either an db.Entity or an SkeletonInstance (if that query has been created by skel.all())

Warning: If your query has an sortOrder other than __key__ and you modify that property here it is possible to encounter that object later one again (as it may jump behind the current cursor).

Parameters:
classmethod handleFinish(totalCount, customData)

Overridable hook that indicates the current run has been finished.

Parameters:
  • totalCount (int) –

  • customData (dict[str, str]) –

class core.skeleton.TaskVacuumRelations

Bases: TaskUpdateSearchIndex

Checks entries in viur-relations and verifies that the src-kind and it’s RelationalBone still exists.

key = 'vacuumRelations'
name = 'Vacuum viur-relations (dangerous)'
descr = 'Drop stale inbound relations for the given kind'
execute(module, *args, **kwargs)

The actual code that should be run goes here.

Parameters:

module (str) –

core.skeleton.processVacuumRelationsChunk(module, cursor, count_total=0, count_removed=0, notify=None)

Processes 25 Entries and calls the next batch

Parameters:
  • module (str) –

  • count_total (int) –

  • count_removed (int) –

core.skeleton.__DEPRECATED_NAMES
core.skeleton.__getattr__(attr)
Parameters:

attr (str) –

Return type:

object