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 VRegistry 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 VRegistry 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 VRegistry instance given as argument (usually named vreg):
register all objects given. Objects which are not from the module modname or which are in butclasses won’t be registered.
Typical usage is:
vreg.register_all(globals().values(), __name__, (ClassIWantToRegisterExplicitly,))
So you get partially automatic registration, keeping manual registration for some object (to use register_and_replace() for instance)
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.
Examples:
# web/views/basecomponents.py
def registration_callback(vreg):
# register everything in the module except SeeAlsoComponent
vreg.register_all(globals().values(), __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 not object with id <oid> in <registry>
raise NoSelectableObject if not object apply
return object with the oid identifier. Only one object is expected to be found.
raise ObjectNotFound if not object with id <oid> in <registry>
raise AssertionError if there is more than one object there
You can combine selectors using the &, | and ~ operators.
When two selectors are combined using the & operator, it means that both should return a positive score. On success, the sum of scores is returned.
When two selectors 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 selector 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 selector, 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_selector() decorator turn it into a proper selector class:
@objectify_selector
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 be then be referenced as set of expected values, allowing modification to the given set to be considered.
You should implement the _get_value(cls, req, **kwargs)() method which should return the value for the given context. The selector will then return 1 if the value is expected, else 0.
abstract class for selectors working on entity class(es) specified explicitly or found of the result set.
Here are entity lookup / scoring rules:
abstract class for selectors working on entity instance(s) specified explicitly or found of the result set.
Here are entity lookup / scoring rules:
Note
using EntitySelector or EClassSelector as base selector 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.
Also, think to use the lltrace() decorator on your selector class’ __call__() method or below the objectify_selector() decorator of your selector function so it gets traceable when traced_selection is activated (see Debugging selection).
Note
Selectors __call__ should always return a positive integer, and shall never return None.
Once in a while, one needs to understand why a view (or any application object) is, or is not selected appropriately. Looking at which selectors fired (or did not) is the way. The cubicweb.appobject.traced_selection context manager to help with that, if you’re running your instance in debug mode.
Typical usage is :
>>> from cubicweb.selectors 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 'cubicweb.web.views.basecomponents.WFHistoryVComponent'>
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 usefull point to set up such a tracing function is the cubicweb.vregistry.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 according to a context (usually at least a request and a result set).
The following attributes should be set on concret appobject classes:
Moreover, the __abstract__ attribute may be set to True to indicate that a class is abstract and should not be registered.
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
do not inherit directly from this class but from a more specific class such as AnyEntity, EntityView, AnyRsetView, Action...
to be recordable, a subclass has to define its registry (attribute __registry__) and its identifier (attribute __regid__). Usually you don’t have to take care of the registry since it’s set by the base class, only the identifier id
application objects are designed to be loaded by the vregistry and should be accessed through it, not by direct instantiation, besides to use it as base classe.
When we inherit from AppObject (even not directly), you always have to use super() to get the methods and attributes of the superclasses, and not use the class identifier.
For example, instead of writting:
class Truc(PrimaryView):
def f(self, arg1):
PrimaryView.f(self, arg1)
You must write:
class Truc(PrimaryView):
def f(self, arg1):
super(Truc, self).f(arg1)
Selectors are scoring functions that are called by the registry to tell whenever an appobject can be selected in a given context. Selector sets are for instance the glue that tie views to the data model. 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 selectors as your needs grows and you get familiar with the framework (see Defining your own selectors).
Here is a description of generic selectors provided by CubicWeb that should suit most of your needs.
Those selectors are somewhat dumb, which doesn’t mean they’re not (very) useful.
Return the score given as parameter, with a default score of 0.5 so any other selector take precedence.
Usually used for appobjects which can be selected whatever the context, or also sometimes to add arbitrary points to a score.
Take care, yes(0) could be named ‘no’...
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:
Those selectors 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 selectors 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 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.
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
Those selectors 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 EClassSelector 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 EClassSelector 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 selector that will usually interest you since it allows a lot of things without having to write a specific selector.
The function can return arbitrary value which will be casted to an integer value at the end.
See EntitySelector 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 selector which will benefit from the ORM’s request entities cache.
See EntitySelector 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 EntitySelector behaviour while otherwise you get the EClassSelector‘s one. See those classes documentation for entity lookup / score rules according to the input context.
Same as :class:~`cubicweb.selectors.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 selector 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 EntitySelector documentation for entity lookup / score rules according to the input context.
Same as :class:~`cubicweb.selectors.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 selector 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 EClassSelector 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 selector to avoid some gotchas:
In debug mode, this selector 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 the name tr_name.
If from_state_name is specified, this selector will also check the incoming state.
You should use this selector 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.
Return non-zero score for entity that are of the given type(s) or implements at least one of the given interface(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 entity types registry at selection time.
See EClassSelector documentation for entity class lookup / score rules according to the input context.
Note
when interface is an entity class, the score will reflect class proximity so the most specific object will be selected.
Note
deprecated in cubicweb >= 3.9, use either is_instance or adaptable.
Those selectors are looking for properties of the user issuing the request.
Return 1 if the user is not authenticated (e.g. 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 (e.g. not the anonymous user).
May only be used on the web side, not on the data repository side.
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 selectors are looking for properties of web request, they can not be used on the data repository side.
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 selector is usually used by action that want to appears or not according to the ui search state.
Return 1 if:
This selector is usually used by contextual components that want to appears in a configurable place.
Return 1 if:
This selector is usually used by contextual components that only want to appears for the primary view of an entity.
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 selector 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 selector is expected to be used to customise the status change form in the web ui.
You’ll also find some other (very) specific selectors hidden in other modules than cubicweb.selectors.