core.skeleton¶
Submodules¶
Attributes¶
TypeVar for generic skeleton typing. |
|
Classes¶
Adapter class used to bind or use other databases and hook operations when working with a Skeleton. |
|
This Adapter implements a simple fulltext search on top of the datastore. |
|
This is a container-object holding information about one database entity. |
|
The actual wrapper around a Skeleton-Class. |
|
This is the metaclass for Skeletons. |
|
This is the metaclass for Skeletons. |
|
This is a Skeleton-like class that acts as a container for Skeletons used as a |
|
This is a Skeleton-like class that acts as a container for Skeletons used as a |
|
Special kind of StringBone saving its contents as viurCurrentSeoKeys into the entity's viur dict. |
|
Iterates the skeletons of a query, and additionally checks a Logics expression. |
|
Base class for user-callable tasks. |
|
A typed list of |
Functions¶
|
This function updates Entities, which may have a copy of values from another entity which has been recently |
|
Checks whether an object is an SkeletonInstance that belongs to a specific Skeleton class. |
Remove renderPreparation of nested skeletons |
|
|
Returns the Skeleton-Class for the given kindName. That skeleton must exist, otherwise an exception is raised. |
|
Return the SkeletonInstance without renderPreparation. |
Package Contents¶
- 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)
- abstractmethod 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 (core.db.Query)
- Return type:
list[core.db.Entity]
- class core.skeleton.ViurTagsSearchAdapter(min_length=2, max_length=50, substring_matching=False)¶
Bases:
DatabaseAdapterThis 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¶
Set to True if we can run a fulltext search using this database.
- fulltextSearchGuaranteesQueryConstrains = True¶
Are results returned by meth:fulltextSearch guaranteed to also match the databaseQuery
- min_length = 2¶
- max_length = 50¶
- substring_matching = False¶
- _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 (core.db.Query)
- Return type:
list[core.db.Entity]
- class core.skeleton.BaseSkeleton¶
Bases:
objectThis 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 = None¶
- classmethod subSkel(*subskel_names, fullClone=False, **kwargs)¶
- Parameters:
fullClone (bool)
- Return type:
- 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.
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.
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.
Both modes (1 + 2) can be combined, but then the original order of the bones is kept.
The “key” bone is automatically available in each sub-skeleton.
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:
- 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
- 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 (core.skeleton.instance.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[t.Self])
- classmethod readonly(skel)¶
Set all bones to readonly in the Skeleton.
- Parameters:
- class core.skeleton.SkeletonInstance(skel_cls, entity=None, *, bones=(), bone_map=None, clone=False, clonedBoneMap=None)¶
Bases:
Generic[core.skeleton.meta.Skeleton_Cls]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.
The class is generic over
Skeleton_Cls, which lets the type checker track which concrete Skeleton subclass a given instance belongs to. Without the type parameter the class still works exactly as before — the parameter is purely a static-analysis hint.Basic usage
Calling a Skeleton class returns a typed
SkeletonInstance:skel = ProductSkel() # -> SkeletonInstance[ProductSkel] skel.skeletonCls # ProductSkel skel["price"] # type-safe bone access
Typed module method
Override
viewSkel/editSkeletc. in your module with an explicit return type so that callers and IDE auto-complete know which bones are available:class ProductModule(List): def editSkel(self) -> SkeletonInstance[ProductSkel]: skel = super().editSkel() skel.price.readOnly = True return skel
Generic helper
Use
Skeleton_Clswhen writing utilities that must stay agnostic about the concrete skeleton but still preserve the type through the call:def set_owner(skel: SkeletonInstance[Skeleton_Cls], owner: str) -> SkeletonInstance[Skeleton_Cls]: skel = skel.clone() skel["owner"] = owner return skel # type checker keeps SkeletonInstance[ProductSkel] etc.
Classmethod signatures (
t.Self)Inside Skeleton classmethods,
t.Selfis preferred overSkeleton_Clsbecause the type checker automatically narrows to the class the method is called on:class BaseSkeleton: @classmethod def fromClient(cls, skel: SkeletonInstance[t.Self], data: dict) -> bool: ... # Inferred as SkeletonInstance[ProductSkel] when called on ProductSkel ProductSkel.fromClient(skel, request.POST)
Creates a new SkeletonInstance based on skel_cls.
- Parameters:
skel_cls (Type[core.skeleton.meta.Skeleton_Cls]) – 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, core.bones.base.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.
entity (Optional[viur.core.db.Entity | dict])
clonedBoneMap (Optional[Dict[str, core.bones.base.BaseBone]])
- __slots__¶
- _cascade_deletion = False¶
- accessedValues¶
- dbEntity = None¶
- errors = []¶
- is_cloned = False¶
- renderAccessedValues¶
- renderPreparation = None¶
- skeletonCls: Type[core.skeleton.meta.Skeleton_Cls]¶
- items(yieldBoneValues=False)¶
- Parameters:
yieldBoneValues (bool)
- Return type:
Iterable[tuple[str, core.bones.base.BaseBone]]
- keys()¶
- Return type:
Iterable[str]
- values()¶
- Return type:
Iterable[Any]
- __iter__()¶
- Return type:
Iterable[str]
- __contains__(item)¶
- __bool__()¶
- 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)¶
- __setattr__(key, value)¶
- __repr__()¶
- Return type:
str
- __str__()¶
- Return type:
str
- __len__()¶
- Return type:
int
- __ior__(other)¶
- Parameters:
other (dict | SkeletonInstance | viur.core.db.Entity)
- Return type:
- clone(*, apply_clone_strategy=False)¶
Clones a SkeletonInstance into a modificable, stand-alone instance. This will also allow to modify the underlying data model.
- Parameters:
apply_clone_strategy (bool)
- Return type:
Self
- 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
- dump(*, bones=())¶
Return a JSON-serializable version of the bone values in this skeleton.
The function is not called “to_json()” because the JSON-serializable format can be used for different purposes and renderings, not just JSON.
- Parameters:
bones (Iterable[str]) – Iterable of bone names to include. If None, all bones are dumped.
- Return type:
dict[str, Any]
- __deepcopy__(memodict)¶
- core.skeleton.ABSTRACT_SKEL_CLS_SUFFIX = 'AbstractSkel'¶
- class core.skeleton.MetaBaseSkel(name, bases, dct, **kwargs)¶
Bases:
typeThis is the metaclass for Skeletons. It is used to enforce several restrictions on bone names, etc.
- _skelCache¶
- _allSkelClasses¶
- __reserved_keywords¶
- __allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'¶
- static generate_bonemap(cls)¶
Recursively constructs a dict of bones from
- __setattr__(key, value)¶
- class core.skeleton.MetaSkel(name, bases, dct, **kwargs)¶
Bases:
MetaBaseSkelThis is the metaclass for Skeletons. It is used to enforce several restrictions on bone names, etc.
- core.skeleton.Skeleton_Cls¶
TypeVar for generic skeleton typing.
Use this to annotate functions and classes that work with a specific, but not yet known, Skeleton subclass. The type checker then knows which concrete Skeleton is in use and can validate bone access.
Example — typed helper function:
from viur.core.skeleton import Skeleton_Cls, SkeletonInstance def clone_and_set_owner(skel: SkeletonInstance[Skeleton_Cls], owner: str) -> SkeletonInstance[Skeleton_Cls]: cloned = skel.clone() cloned["owner"] = owner return cloned
Example — typed module override:
class ProductModule(List): def editSkel(self) -> SkeletonInstance[ProductSkel]: skel = super().editSkel() skel.price.readOnly = True return skel
When calling a classmethod on a concrete Skeleton, use
t.Selfinstead so the type checker automatically narrows to the calling class:class BaseSkeleton: @classmethod def fromClient(cls, skel: SkeletonInstance[t.Self], data: dict) -> bool: ... # Calling on a concrete class: type checker knows skel is SkeletonInstance[ProductSkel] ProductSkel.fromClient(skel, request.POST)
- class core.skeleton.RefSkel¶
Bases:
RelSkelThis is a Skeleton-like class that acts as a container for Skeletons used as a additional information data skeleton for
RelationalBone.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.- skeletonCls: Type[core.skeleton.Skeleton] | None = None¶
Reference source skeleton class
- classmethod fromSkel(kindName, *args)¶
Creates a
RefSkelfrom a skeleton-class using only the bones explicitly named inargs.- 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, *, subskel=(), bones=())¶
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.
- Parameters:
key (Optional[core.db.Key | str | int]) – Can be used to overwrite the key; Ohterwise, the RefSkel’s key-property will be used.
subskel (Iterable[str]) – Optionally form skel from subskels
bones (Iterable[str]) – Optionally create skeleton only from the specified bones
- Raises:
ValueError – If the entry is no longer in the database.
- Return type:
- class core.skeleton.RelSkel¶
Bases:
core.skeleton.base.BaseSkeletonThis is a Skeleton-like class that acts as a container for Skeletons used as a additional information data skeleton for
RelationalBone.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 (core.db.Entity | dict) – dict with values we’ll assign to our bones
- class core.skeleton.SeoKeyBone(*, caseSensitive=True, max_length=254, min_length=None, natural_sorting=False, escape_html=None, **kwargs)¶
Bases:
core.bones.string.StringBoneSpecial 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.
escape_html (bool | None) – Replace some characters in the string with HTML-safe sequences with using
utils.string.escape()for safe use in HTML. Defaults toconf.bone_string_escape_htmlif not set explicitly.kwargs – Inherited arguments from the BaseBone.
- setSystemInitialized()¶
For the BaseBone, this performs some automatisms regarding bone descr and translations. It can be overwritten to initialize properties that depend on the Skeleton system being initialized.
- 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 (core.skeleton.instance.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 (core.skeleton.instance.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:
core.skeleton.base.BaseSkeleton- kindName: str¶
Specifies the entity kind name this Skeleton is associated with. Will be determined automatically when not explicitly set.
- database_adapters: core.skeleton.adapter.DatabaseAdapter | Iterable[core.skeleton.adapter.DatabaseAdapter] | None¶
Custom database adapters. Allows to hook special functionalities that during skeleton modifications.
- subSkels¶
- interBoneValidations: list[Callable[[Skeleton], list[core.bones.base.ReadFromClientError]]] = []¶
- __seo_key_trans¶
- key¶
- shortkey¶
- name¶
- creationdate¶
- changedate¶
- viurCurrentSeoKeys¶
- __repr__()¶
- __str__()¶
- 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[t.Self]) – 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:
key (viur.core.db.KeyType)
- 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[viur.core.db.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[[core.skeleton.instance.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.
_check_legacy (bool)
- Returns:
None on error, or the given SkeletonInstance on success.
- Return type:
Optional[core.skeleton.instance.SkeletonInstance]
- classmethod toDB(skel, update_relations=True, **kwargs)¶
Deprecated function, replaced by Skeleton.write().
- Parameters:
update_relations (bool)
- 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[viur.core.db.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.
_check_legacy (bool)
- Returns:
The Skeleton.
- Return type:
- classmethod delete(skel, key=None)¶
Deletes the entity associated with the current Skeleton from the data store.
- Parameters:
key (Optional[viur.core.db.KeyType]) – Allows to specify a key that is used for deletion, otherwise skel[“key”] will be used.
- Return type:
None
- classmethod patch(skel, values={}, *, check=None, create=None, ignore=(), internal=True, key=None, preprocess=None, retry=0, update_relations=True)¶
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[[core.skeleton.instance.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.KeyType]) – 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[[core.skeleton.instance.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[[core.skeleton.instance.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.
ignore (Optional[Iterable[str]]) – optional list of bones to be ignored from values; Defaults to an empty list, so that all bones are accepted (even read-only ones, as skel.patch() is being used internally)
internal (bool) – Internal patch does ignore any NotSet and Empty errors that may raise in skel.fromClient()
retry (int) – On RuntimeError, retry for this amount of times. - DEPRECATED!
preprocess (Optional[Callable[[core.skeleton.instance.SkeletonInstance], None]])
- Return type:
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:
- classmethod preProcessSerializedData(skel, entity)¶
Can be overridden to modify the
viur.core.db.Entitybefore its actually written to the data store.- Parameters:
- classmethod postSavedHandler(skel, key, dbObj)¶
Can be overridden to perform further actions after the entity has been written to the data store.
- Parameters:
- classmethod postDeletedHandler(skel, key)¶
Can be overridden to perform further actions after the entity has been deleted from the data store.
- Parameters:
- 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:
- Return type:
None | dict[str, str]
- core.skeleton._UNDEFINED_KINDNAME¶
- class core.skeleton.SkelIterTask¶
Bases:
viur.core.tasks.QueryIterIterates the skeletons of a query, and additionally checks a Logics expression. When the skeleton is valid, it performs the action data[“action”] on each entry.
- classmethod handleEntry(skel, data)¶
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).
- classmethod handleError(skel, data, exception)¶
Handle a error occurred in handleEntry. If this function returns True, the queryIter continues, otherwise it breaks and prints the current cursor.
- Return type:
bool
- classmethod handleFinish(total, data)¶
Overridable hook that indicates the current run has been finished.
- class core.skeleton.SkeletonMaintenanceTask¶
Bases:
viur.core.tasks.CallableTaskBaseBase class for user-callable tasks. Must be subclassed.
- key = 'SkeletonMaintenanceTask'¶
- name = 'Skeleton Maintenance'¶
- descr = 'Perform filtered maintenance operations on skeletons.'¶
- canCall()¶
Checks wherever the current user can execute this task :returns: bool
- class dataSkel¶
Bases:
core.skeleton.relskel.RelSkelIf additional data is needed, return a skeleton-instance here. These values are then passed to execute.
- task¶
- kinds¶
- class FilterRowUsingSkel¶
Bases:
core.skeleton.relskel.RelSkel- name¶
- op¶
- value¶
- filters¶
- condition¶
- execute(task, kinds, filters, condition)¶
The actual code that should be run goes here.
- core.skeleton.update_relations(key, *, min_change_time=None, changed_bones=(), cursor=None, total=0, **kwargs)¶
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:
key (viur.core.db.Key) – The database-key of the entity that has been edited
min_change_time (Optional[float]) – 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 up-to-date
changed_bones (Optional[Iterable[str] | str]) – If set, we’ll update only entites that have a copy of that bones. 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.
total (int)
- class core.skeleton.SkelList(skel=None, *items)¶
Bases:
list,Generic[core.skeleton.meta.Skeleton_Cls]A typed list of
SkeletonInstanceobjects with query metadata.Returned by
Skel().all()...fetch()constructs. The generic parameter mirrors the one onSkeletonInstanceso that the element type flows through without manual casts:result: SkelList[ProductSkel] = ProductSkel().all().fetch(10) for skel in result: # skel is SkeletonInstance[ProductSkel] print(skel["price"])
Without the type parameter the class behaves exactly as before.
- Variables:
baseSkel – The base skeleton instance used to construct this list.
getCursor – Callable returning the datastore cursor for pagination.
get_orders – Callable returning the active query ordering.
renderPreparation – Render-preparation callback, set by renderers.
customQueryInfo – Arbitrary extra metadata attached by query helpers.
- Parameters:
baseSkel – The baseclass for all entries in this list
skel (Optional[SkeletonInstance[Skeleton_Cls]])
- __slots__ = ('baseSkel', 'customQueryInfo', 'getCursor', 'get_orders', 'renderPreparation')¶
- baseSkel: SkeletonInstance[Skeleton_Cls] | dict¶
- getCursor¶
- get_orders¶
- renderPreparation = None¶
- customQueryInfo¶
- core.skeleton.is_skeletoninstance_of(obj, skel_cls, *, accept_ref_skel=True)¶
Checks whether an object is an SkeletonInstance that belongs to a specific Skeleton class.
- Parameters:
obj (Any) – The object to check.
skel_cls (type[core.skeleton.Skeleton]) – The skeleton class that will be checked against
obj.accept_ref_skel (bool) – If True,
objcan also be just a RefSkelFor``skel_cls``. If False, noRefSkelis accepted.
- Return type:
bool
- 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[core.skeleton.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.remove_render_preparation_deep(skel)¶
Remove renderPreparation of nested skeletons
_refSkelCache can have renderPreparation too.
- Parameters:
skel (Any)
- Return type:
Any
- 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[core.skeleton.Skeleton]
- core.skeleton.without_render_preparation(skel, full_clone=False)¶
Return the SkeletonInstance without renderPreparation.
This method is useful (and unfortunately necessary due to the ViUR design) if you call python methods from the jinja template that should work on the SkeletonInstance.accessedValues and not on the SkeletonInstance.renderAccessedValues.
If the SkeletonInstance does not have renderPreparation, it will be returned as is. If renderPreparation is enabled, a new SkeletonInstance is created. However, unless full_clone is True, the SkeletonInstance will use the identical objects as the source skeleton. It just “removes” the “renderPreparation mode” and keep it for the source skel enabled.
- Parameters:
full_clone (bool)
- Return type: