This chapter deals with some of the core concepts of the CubicWeb framework which make it different from other frameworks (and maybe not easy to grasp at a first glance). To be able to do advanced development with CubicWeb you need a good understanding of what is explained below.
This chapter goes deep into details. You don’t have to remember them all but keep it in mind so you can go back there later.
An overview of AppObjects, the VRegistry and Selectors is given in the Registries and application objects chapter.
The RegistryStore can be seen as a two-level dictionary. It contains all dynamically loaded objects (subclasses of The AppObject class) to build a CubicWeb application. Basically:
A registry holds a specific kind of application objects. There is for instance a registry for entity classes, another for views, etc...
The RegistryStore has two main responsibilities:
On startup, CubicWeb loads application objects defined in its library and in cubes used by the instance. Application objects from the library are loaded first, then those provided by cubes are loaded in dependency order (e.g. if your cube depends on an other, objects from the dependency will be loaded first). The layout of the modules or packages in a cube is explained in Standard structure for a cube.
For each module:
Note
Once the function registration_callback(vreg) is implemented in a module, all the objects from this module have to be explicitly registered as it disables the automatic objects registration.
Here are the registration methods that you can use in the registration_callback to register your objects to the RegistryStore instance given as argument (usually named vreg):
register obj application object into registryname or obj.__registry__ if not specified, with identifier oid or obj.__regid__ if not specified.
If clear is true, all objects with the same identifier will be previously unregistered.
unregister obj object from the registry registryname or obj.__registries__ if not specified.
Examples:
# web/views/basecomponents.py
def registration_callback(vreg):
# register everything in the module except SeeAlsoComponent
vreg.register_all(globals().itervalues(), __name__, (SeeAlsoVComponent,))
# conditionally register SeeAlsoVComponent
if 'see_also' in vreg.schema:
vreg.register(SeeAlsoVComponent)
In this example, we register all application object classes defined in the module except SeeAlsoVComponent. This class is then registered only if the ‘see_also’ relation type is defined in the instance’schema.
# goa/appobjects/sessions.py
def registration_callback(vreg):
vreg.register(SessionsCleaner)
# replace AuthenticationManager by GAEAuthenticationManager
vreg.register_and_replace(GAEAuthenticationManager, AuthenticationManager)
# replace PersistentSessionManager by GAEPersistentSessionManager
vreg.register_and_replace(GAEPersistentSessionManager, PersistentSessionManager)
In this example, we explicitly register classes one by one:
If at some point we register a new appobject class in this module, it won’t be registered at all without modification to the registration_callback implementation. The previous example will register it though, thanks to the call to the register_all method.
Now that we have all application objects loaded, the question is : when I want some specific object, for instance the primary view for a given entity, how do I get the proper object ? This is what we call the selection mechanism.
As explained in the The Core Concepts of CubicWeb section:
Note
When no single object has the highest score, an exception is raised in development mode to let you know that the engine was not able to identify the view to apply. This error is silenced in production mode and one of the objects with the highest score is picked.
In such cases you would need to review your design and make sure your selectors or appobjects are properly defined. Such an error is typically caused by either forgetting to change the __regid__ in a derived class, or by having copy-pasted some code.
For instance, if you are selecting the primary (__regid__ = ‘primary’) view (__registry__ = ‘views’) for a result set containing a Card entity, two objects will probably be selectable:
Other primary views specific to other entity types won’t be selectable in this case. Among selectable objects, the is_instance(‘Card’) selector will return a higher score since it’s more specific, so the correct view will be selected as expected.
Here is the selection API you’ll get on every registry. Some of them, as the ‘etypes’ registry, containing entity classes, extend it. In those methods, *args, **kwargs is what we call the context. Those arguments are given to selectors that will inspect their content and return a score accordingly.
return the most specific object among those with the given oid according to the given context.
raise ObjectNotFound if there are no object with id oid in this registry
raise NoSelectableObject if no object can be selected
return the most specific object among those with the given oid according to the given context, or None if no object applies.
return an iterator on possible objects in this registry for the given context
return object with the oid identifier. Only one object is expected to be found.
raise ObjectNotFound if there are no object with id oid in this registry
raise AssertionError if there is more than one object there
A predicate is a class testing a particular aspect of a context. A selector is built by combining existant predicates or even selectors.
You can combine predicates using the &, | and ~ operators.
When two predicates are combined using the & operator, it means that both should return a positive score. On success, the sum of scores is returned.
When two predicates are combined using the | operator, it means that one of them should return a positive score. On success, the first positive score is returned.
You can also “negate” a predicate by precedeing it by the ~ unary operator.
Of course you can use parenthesis to balance expressions.
The goal: when on a blog, one wants the RSS link to refer to blog entries, not to the blog entity itself.
To do that, one defines a method on entity classes that returns the RSS stream url for a given entity. The default implementation on AnyEntity (the generic entity class used as base for all others) and a specific implementation on Blog will do what we want.
But when we have a result set containing several Blog entities (or different entities), we don’t know on which entity to call the aforementioned method. In this case, we keep the generic behaviour.
Hence we have two cases here, one for a single-entity rsets, the other for multi-entities rsets.
In web/views/boxes.py lies the RSSIconBox class. Look at its selector:
class RSSIconBox(box.Box):
''' just display the RSS icon on uniform result set '''
__select__ = box.Box.__select__ & non_final_entity()
It takes into account:
This matches our second case. Hence we have to provide a specific component for the first case:
class EntityRSSIconBox(RSSIconBox):
'''just display the RSS icon on uniform result set for a single entity'''
__select__ = RSSIconBox.__select__ & one_line_rset()
Here, one adds the one_line_rset predicate, which filters result sets of size 1. Thus, on a result set containing multiple entities, one_line_rset makes the EntityRSSIconBox class non selectable. However for a result set with one entity, the EntityRSSIconBox class will have a higher score than RSSIconBox, which is what we wanted.
Of course, once this is done, you have to:
Selectors are to be used whenever arises the need of dispatching on the shape or content of a result set or whatever else context (value in request form params, authenticated user groups, etc...). That is, almost all the time.
Here is a quick example:
class UserLink(component.Component):
'''if the user is the anonymous user, build a link to login else a link
to the connected user object with a logout link
'''
__regid__ = 'loggeduserlink'
def call(self):
if self._cw.session.anonymous_session:
# display login link
...
else:
# display a link to the connected user object with a loggout link
...
The proper way to implement this with CubicWeb is two have two different classes sharing the same identifier but with different selectors so you’ll get the correct one according to the context.
class UserLink(component.Component):
'''display a link to the connected user object with a loggout link'''
__regid__ = 'loggeduserlink'
__select__ = component.Component.__select__ & authenticated_user()
def call(self):
# display useractions and siteactions
...
class AnonUserLink(component.Component):
'''build a link to login'''
__regid__ = 'loggeduserlink'
__select__ = component.Component.__select__ & anonymous_user()
def call(self):
# display login link
...
The big advantage, aside readability once you’re familiar with the system, is that your cube becomes much more easily customizable by improving componentization.
Most of the time, a simple score function is enough to build a selector. The objectify_predicate() decorator turn it into a proper selector class:
@objectify_predicate
def one(cls, req, rset=None, **kwargs):
return 1
class MyView(View):
__select__ = View.__select__ & one()
In other cases, you can take a look at the following abstract base classes:
Take a list of expected values as initializer argument and store them into the expected set attribute. You may also give a set as single argument, which will then be referenced as set of expected values, allowing modifications to the given set to be considered.
You should implement one of _values_set(cls, req, **kwargs)() or _get_value(cls, req, **kwargs)() method which should respectively return the set of values or the unique possible value for the given context.
You may also specify a mode behaviour as argument, as explained below.
Returned score is:
Notice mode = ‘any’ with a single expected value has no effect at all.
abstract class for predicates working on entity class(es) specified explicitly or found of the result set.
Here are entity lookup / scoring rules:
When there are several classes to be evaluated, return the sum of scores for each entity class unless:
- mode == ‘all’ (the default) and some entity class is scored to 0, in which case 0 is returned
- mode == ‘any’, in which case the first non-zero score is returned
- accept_none is False and some cell in the column has a None value (this may occurs with outer join)
abstract class for predicates working on entity instance(s) specified explicitly or found of the result set.
Here are entity lookup / scoring rules:
Note
using EntityPredicate or EClassPredicate as base predicate class impacts performance, since when no entity or row is specified the later works on every different entity class found in the result set, while the former works on each entity (eg each row of the result set), which may be much more costly.
Once in a while, one needs to understand why a view (or any application object) is, or is not selected appropriately. Looking at which predicates fired (or did not) is the way. The logilab.common.registry.traced_selection context manager to help with that, if you’re running your instance in debug mode.
Typical usage is :
>>> from logilab.common.registry import traced_selection
>>> with traced_selection():
... # some code in which you want to debug selectors
... # for all objects
Don’t forget the ‘from __future__ import with_statement’ at the module top-level if you’re using python prior to 2.6.
This will yield lines like this in the logs:
selector one_line_rset returned 0 for <class 'elephant.Babar'>
You can also give to traced_selection the identifiers of objects on which you want to debug selection (‘oid1’ and ‘oid2’ in the example above).
>>> with traced_selection( ('regid1', 'regid2') ):
... # some code in which you want to debug selectors
... # for objects with __regid__ 'regid1' and 'regid2'
A potentially useful point to set up such a tracing function is the logilab.common.registry.Registry.select method body.
The AppObject class is the base class for all dynamically loaded objects (application objects) accessible through the vregistry.
We can find a certain number of attributes and methods defined in this class and common to all the application objects.
This is the base class for CubicWeb application objects which are selected in a request context.
The following attributes should be set on concrete appobject classes:
At selection time, the following attributes are set on the instance:
And also the following, only if rset is found in arguments (in which case rset/row/col will be removed from cwextra_kwargs):
Note
Predicates are scoring functions that are called by the registry to tell whenever an appobject can be selected in a given context. Predicates may be chained together using operators to build a selector. A selector is the glue that tie views to the data model or whatever input context. Using them appropriately is an essential part of the construction of well behaved cubes.
Of course you may have to write your own set of predicates as your needs grows and you get familiar with the framework (see Defining your own predicates).
Here is a description of generic predicates provided by CubicWeb that should suit most of your needs.
Those predicates are somewhat dumb, which doesn’t mean they’re not (very) useful.
alias of wrapped
Return non-zero score if parameter names specified as initializer arguments are specified in the input context.
Return a score corresponding to the number of expected parameters.
When multiple parameters are expected, all of them should be found in the input context unless mode keyword argument is given to ‘any’, in which case a single matching parameter is enough.
Return 1 if another appobject is selectable using the same input context.
Initializer arguments:
Return 1 if another appobject is selectable using the same input context.
Initializer arguments:
Return 1 if the instance has an option set to a given value(s) in its configuration file.
Those predicates are looking for a result set in the context (‘rset’ argument or the input context) and match or not according to its shape. Some of these predicates have different behaviour if a particular cell of the result set is specified using ‘row’ and ‘col’ arguments of the input context or not.
Return 1 if the result set is None (eg usually not specified).
Return 1 for any result set, whatever the number of rows in it, even 0.
Return 1 for result set containing one ore more rows.
Return 1 for result set which doesn’t contain any row.
Return 1 if the result set is of size 1, or greater but a specific row in the result set is specified (‘row’ argument).
Return 1 if the operator expression matches between num elements in the result set and the expected value if defined.
If expected is None, return 1 if the result set contains at least two rows. If rset is None, return 0.
If nb is specified, return 1 if the result set has exactly nb column per row. Else (nb is None), return 1 if the result set contains at least two columns per row. Return 0 for empty result set.
Return 1 or more for result set with more rows than one or more page size. You can specify expected number of pages to the initializer (default to one), and you’ll get that number of pages as score if the result set is big enough.
Page size is searched in (respecting order): * a page_size argument * a page_size form parameters * the navigation.page-size property (see Configuring persistent properties)
Return 1 for sorted result set (e.g. from an RQL query containing an ORDERBY clause), with exception that it will return 0 if the rset is ‘ORDERBY FTIRANK(VAR)’ (eg sorted by rank value of the has_text index).
Return 1 if the result set contains entities which are all of the same type in the column specified by the col argument of the input context, or in column 0.
If nb is specified, return 1 if the result set contains nb different types of entities in the column specified by the col argument of the input context, or in column 0. If nb is None, return 1 if the result set contains at least two different types of entities.
Those predicates are looking for either an entity argument in the input context, or entity found in the result set (‘rset’ argument or the input context) and match or not according to entity’s (instance or class) properties.
Return 1 for entity of a non final entity type(s). Remember, “final” entity types are String, Int, etc... This is equivalent to is_instance(‘Any’) but more optimized.
See EClassPredicate documentation for entity class lookup / score rules according to the input context.
Return non-zero score for entity that is an instance of the one of given type(s). If multiple arguments are given, matching one of them is enough.
Entity types should be given as string, the corresponding class will be fetched from the registry at selection time.
See EClassPredicate documentation for entity class lookup / score rules according to the input context.
Note
the score will reflect class proximity so the most specific object will be selected.
Return score according to an arbitrary function given as argument which will be called with input content entity as argument.
This is a very useful predicate that will usually interest you since it allows a lot of things without having to write a specific predicate.
The function can return arbitrary value which will be casted to an integer value at the end.
See EntityPredicate documentation for entity lookup / score rules according to the input context.
Return non-zero score if arbitrary rql specified in expression initializer argument return some results for entity found in the input context. Returned score is the number of items returned by the rql condition.
expression is expected to be a string containing an rql expression, which must use ‘X’ variable to represent the context entity and may use ‘U’ to represent the request’s user.
Warning
If simply testing value of some attribute/relation of context entity (X), you should rather use the score_entity predicate which will benefit from the ORM’s request entities cache.
See EntityPredicate documentation for entity lookup / score rules according to the input context.
Return 1 for entity that supports the relation, provided that the request’s user may do some action on it (see below).
The relation is specified by the following initializer arguments:
Setting strict to True impacts performance for large result set since you’ll then get the EntityPredicate behaviour while otherwise you get the EClassPredicate‘s one. See those classes documentation for entity lookup / score rules according to the input context.
Same as :class:~`cubicweb.predicates.relation_possible`, but will look for attributes of the selected class to get information which is otherwise expected by the initializer, except for action and strict which are kept as initializer arguments.
This is useful to predefine predicate of an abstract class designed to be customized.
Return 1 if entity support the specified relation and has some linked entities by this relation , optionaly filtered according to the specified target type.
The relation is specified by the following initializer arguments:
See EntityPredicate documentation for entity lookup / score rules according to the input context.
Same as :class:~`cubicweb.predicates.has_related_entity`, but will look for attributes of the selected class to get information which is otherwise expected by the initializer.
This is useful to predefine predicate of an abstract class designed to be customized.
Return non-zero score if request’s user has the permission to do the requested action on the entity. action is an entity schema action (eg one of ‘read’, ‘add’, ‘delete’, ‘update’).
Here are entity lookup / scoring rules:
Return 1 if request’s user has the add permission on entity type specified in the etype initializer argument, or according to entity found in the input content if not specified.
It also check that then entity type is not a strict subobject (e.g. may only be used as a composed of another entity).
See EClassPredicate documentation for entity class lookup / score rules according to the input context when etype is not specified.
Return 1 if the entity adapt to IDownloadable and has the given MIME type.
You can give ‘image/’ to match any image for instance, or ‘image/png’ to match only PNG images.
Return 1 if entity is in one of the states given as argument list
You should use this instead of your own score_entity predicate to avoid some gotchas:
In debug mode, this predicate can raise ValueError for unknown states names (only checked on entities without a custom workflow)
Return type: | int |
---|
Return 1 when entity of the type etype is going through transition of a name included in tr_names.
You should use this predicate on ‘after_add_entity’ hook, since it’s actually looking for addition of TrInfo entities. Hence in the hook, self.entity will reference the matching TrInfo entity, allowing to get all the transition details (including the entity to which is applied the transition but also its original state, transition, destination state, user...).
See cubicweb.entities.wfobjs.TrInfo for more information.
Those predicates are looking for properties of the user issuing the request.
Return a non-zero score if request’s user is in at least one of the groups given as initializer argument. Returned score is the number of groups in which the user is.
If the special ‘owners’ group is given and rset is specified in the input context:
Those predicates are looking for properties of web request, they can not be used on the data repository side.
Return 1 if the web session has no connection set. This occurs when anonymous access is not allowed and user isn’t authenticated.
May only be used on the web side, not on the data repository side.
Return 1 if the user is not authenticated (i.e. is the anonymous user).
May only be used on the web side, not on the data repository side.
Return 1 if the user is authenticated (i.e. not the anonymous user).
May only be used on the web side, not on the data repository side.
Return non-zero score if parameter names specified as initializer arguments are specified in request’s form parameters.
Return a score corresponding to the number of expected parameters.
When multiple parameters are expected, all of them should be found in the input context unless mode keyword argument is given to ‘any’, in which case a single matching parameter is enough.
Return 1 if the current request search state is in one of the expected states given to the initializer.
Known search states are either ‘normal’ or ‘linksearch’ (eg searching for an object to create a relation with another).
This predicate is usually used by action that want to appears or not according to the ui search state.
Return 1 if:
This predicate is usually used by contextual components that want to appears in a configurable place.
Return 1 if a view is specified an as its registry id is in one of the expected view id given to the initializer.
Return 1 if:
This predicate is usually used by contextual components that only want to appears for the primary view of an entity.
Return 1 if view’s contextual property is true
Return non-zero score if the entity type specified by an ‘etype’ key searched in (by priority) input context kwargs and request form parameters match a known entity type (case insensitivly), and it’s associated entity class is of one of the type(s) given to the initializer. If multiple arguments are given, matching one of them is enough.
Note
as with is_instance, entity types should be given as string and the score will reflect class proximity so the most specific object will be selected.
This predicate is usually used by views holding entity creation forms (since we’ve no result set to work on).
Scores if the specified attribute has been edited This is useful for selection of forms by the edit controller.
The initial use case is on a form, in conjunction with match_transition, which will not score at edit time:
is_instance('Version') & (match_transition('ready') |
attribute_edited('publication_date'))
Return 1 if transition argument is found in the input context which has a .name attribute matching one of the expected names given to the initializer.
This predicate is expected to be used to customise the status change form in the web ui.
Return 1 if exception given as exc in the input context is an instance of one of the class given on instanciation of this predicate.
Return 1 if running in debug mode.
You’ll also find some other (very) specific predicates hidden in other modules than cubicweb.predicates.