CubicWeb provides a few helpers to facilitate javascript <-> python communications.
You can, for instance, register some python functions that will become callable from javascript through ajax calls. All the ajax URLs are handled by the cubicweb.web.views.ajaxcontroller.AjaxController controller.
The ajaxcontroller module defines the AjaxController controller and the ajax-func cubicweb registry.
AjaxController handles ajax remote calls from javascript
The following javascript function call:
var d = asyncRemoteExec('foo', 12, "hello");
d.addCallback(function(result) {
alert('server response is: ' + result);
});
will generate an ajax HTTP GET on the following url:
BASE_URL/ajax?fname=foo&arg=12&arg="hello"
The AjaxController controller will therefore be selected to handle those URLs and will itself select the cubicweb.web.views.ajaxcontroller.AjaxFunction matching the fname parameter.
ajax-funcs registry hosts exposed remote functions, that is functions that can be called from the javascript world.
To register a new remote function, either decorate your function with the ajaxfunc() decorator:
from cubicweb.predicates import mactch_user_groups
from cubicweb.web.views.ajaxcontroller import ajaxfunc
@ajaxfunc(output_type='json', selector=match_user_groups('managers'))
def list_users(self):
return [u for (u,) in self._cw.execute('Any L WHERE U login L')]
or inherit from AjaxFunction and implement the __call__ method:
from cubicweb.web.views.ajaxcontroller import AjaxFunction
class ListUser(AjaxFunction):
__regid__ = 'list_users' # __regid__ is the name of the exposed function
__select__ = match_user_groups('managers')
output_type = 'json'
def __call__(self):
return [u for (u, ) in self._cw.execute('Any L WHERE U login L')]
Attributes on this base class are:
Attr : | check_pageid: make sure the pageid received is valid before proceeding |
---|---|
Attr : | output_type:
|
promote a standard function to an AjaxFunction appobject.
All parameters are optional:
Parameters: |
|
---|
ajaxfunc can be used both as a standalone decorator:
@ajaxfunc
def my_function(self):
return 42
or as a parametrizable decorator:
@ajaxfunc(output_type='json')
def my_function(self):
return 42