Sijax 0.2.5 documentation

API

«  Upload Plugin   ::   Contents   ::   Frequently Asked Questions and Notes  »

API

Sijax

class sijax.Sijax

The main Sijax object is what manages function registration and calling.

Sijax initialization usually looks like this:

instance = Sijax()
instance.set_data(POST_DICTIONARY_HERE)
instance.set_request_uri(URI_TO_SEND_REQUESTS_TO)
instance.register_callback('function_name', some_function)

Sijax needs the POST parameters for the current request, to determine whether the request is meant to be handled by Sijax or by your regular page loading logic.

Sijax needs a request URI to tell the client where to send the ajax requests. This is usually the current request URI, but another URI can also be used.

Functions that are registered (using sijax.Sijax.register_callback() or sijax.Sijax.register_object()) are the only functions exposed to the browser for calling.

EVENT_AFTER_PROCESSING = 'after_processing'

Event called immediately after calling the response function. The event handler function receives the Response object argument.

EVENT_BEFORE_PROCESSING = 'before_processing'

Event called immediately before calling the response function. The event handler function receives the Response object argument.

EVENT_INVALID_CALL = 'invalid_call'

Event called when the function was called in a wrong way (bad arguments count). The event handler function receives the Response object argument followed by the callback function that was not called correctly.

EVENT_INVALID_REQUEST = 'invalid_request'

Event called when the function to be called is unknown (not registered with Sijax). The event handler function receives the Response object argument followed by the public name of the function that was supposed to be called.

PARAM_ARGS_EXTRA = 'args_extra'

An option when registering callbacks that makes certain extra arguments be passed automatically to the response function after the obj_response argument and before the other arguments

PARAM_CALLBACK = 'callback'

An option when registering callbacks that stores the callback function

PARAM_RESPONSE_CLASS = 'response_class'

An option when registering callbacks that allows the response class to be changed from sijax.response.BaseResponse to something else.

execute_callback(args, callback, **params)

Executes the given callback function and returns a response.

Before executing the given callback, the sijax.Sijax.EVENT_BEFORE_PROCESSING event callback is fired. After executing the given callback, the sijax.Sijax.EVENT_AFTER_PROCESSING event callback is fired.

The returned result could either be a string (for regular functions) or a generator (for streaming functions like Comet or Upload).

Parameters:
  • args – the arguments list to pass to the callback
  • callback – the callback function to execute
  • options – more options - look at sijax.Sijax.register_callback() to see what else is available
Returns:

string for regular callbacks or generator for streaming callbacks

get_data()

Returns the incoming data array that the current instance uses.

get_event(event_name)

Returns the event handler callback for the specified event.

get_js()

Returns the javascript code needed to prepare the Sijax environment in the browser.

Note that the javascript code is unique and cannot be shared between different pages.

has_event(event_name)

Tells whether we’ve got a registered event by that name.

is_sijax_request

Tells whether this page request looks like a valid request meant to be handled by Sijax.

Even if this is a Sijax request, this doesn’t mean it’s a valid one. Refer to sijax.Sijax.process_request() to see what happens when a request for an unknown function was made.

process_request()

Executes the Sijax request and returns the response.

Make sure that the current request is a Sijax request, using sijax.Sijax.is_sijax_request before calling this. A sijax.exception.SijaxError will be raised, if this method is called for non-Sijax requests.

If the function that was called from the browser is not registered (the function is unknown to Sijax), the sijax.Sijax.EVENT_INVALID_REQUEST event handler will be called instead.

Refer to sijax.Sijax.execute_callback() to see how the main handler is called and what the response (return value) is.

register_callback(public_name, callback, response_class=None, args_extra=None)

Registers the specified callback function with the given name.

Example:

def handler(obj_response):
    pass

# Exposing the same function by 2 different names
instance.register_callback('test', handler)
instance.register_callback('test2', handler)

The optional response_class parameter could be used to substitute the sijax.response.BaseResponse class used by default. An instance of response_class is passed automatically as a first parameter to your response function (obj_response).

Example:

def handler(obj_response):
    pass

class MyResponse(sijax.response.BaseResponse):
    pass

# `obj_response` passed to `handler` will be an instance of MyResponse
instance.register_callback('test', handler, response_class=MyResponse)

The optional args_extra parameter allows you to pass a list of extra arguments to your response function, immediately after the obj_response argument and before the other call arguments.

Example:

def handler(obj_response, arg1, arg2, arg3):
    # arg1 = 'arg1'
    # arg2 = 'arg2'
    # arg3 - expected to come from the browser
    pass

instance.register_callback('test', handler, args_extra=['arg1', 'arg2'])
Parameters:
  • public_name – the name with which this function will be exposed in the browser
  • callback – the actual function to call
  • response_class – the response class, an instance of which to use instead of sijax.response.BaseResponse
  • args_extra – an optional list of additional arguments to pass after the response object argument and before the other call arguments
register_event(event_name, callback)

Register a callback function to be called when the event occurs.

Only one callback can be executed per event.

The provided EVENT_* constants should be used for handling system events. Additionally, you can use any string to define your own events and callbacks.

If more than one handler per event is needed, you can chain them manually, although it’s not recommended.

register_object(obj, **options)

Registers all “public” callable attributes of the given object.

The object could be anything (module, class, class instance, etc.)

Parameters:
request_args

The arguments list, that the function was called with in the browser.

It should be noted that this is not necessarily the arguments list that the callback function will actually receive. Custom Response objects are allowed to override the arguments list.

requested_function

The name of the requested function, or None if the current request is not a Sijax request.

set_data(data)

Sets the incoming data dictionary (usually POST).

Sijax needs this data to determine if the current request is a Sijax request, and which callback should be called with what arguments.

set_json_uri(uri)

Sets the URI to an external JSON library, for browsers that do not support native JSON (such as IE <= 7).

If this is not specified, Sijax will not work at all in such browsers.

The script will only be loaded if a browser without JSON support is detected.

set_request_uri(uri)

Specifies the URI where ajax requests will be sent to by the client.

This is usually the URI of the current request.

BaseResponse

class sijax.response.BaseResponse(sijax_instance, request_args)

The response class is the way by which Sijax functions (handlers) pass information back to the browser. They do this by calling various methods, which queue commands until they’re sent to the browser.

alert(message)

Sends a window.alert command to the browser.

Example that shows a message box:

obj_response.alert('Alert message!')
attr(selector, property_name, value)

Assigns an attribute value to all elements matching the jQuery selector.

Same as jQuery’s $(selector).attr('property', 'value')

Example which changes 2 attributes of a given element:

obj_response.attr('#element', 'width', '500px')
obj_response.attr('#element', 'disabled', true)
Parameters:
  • selector – the jQuery selector to invoke attr() on
  • property_name – the name of the property
  • value – the new value to assign to the property
attr_append(selector, property_name, value)

Same as sijax.response.BaseResponse.attr(), but appends instead of assigning a new value.

attr_prepend(selector, property_name, value)

Same as sijax.response.BaseResponse.attr(), but prepends instead of assigning a new value.

call(js_func_name, func_params=None)

Calls the given javascript function with the given arguments list.

Example which calls the browser’s alert() function:

obj_response.call('alert', ['Message'])
Parameters:
  • js_func_name – the name of the javascript function to call
  • func_params – a list of arguments to call the function with
clear_commands()

Clears the commands buffer.

All the commands added by other methods will be removed.

Example:

obj_response.alert('Some alert!')
obj_response.clear_commands()
# The alert() above got removed from the commands queue
css(selector, property_name, value)

Assigns a style property value to all elements matching the jQuery selector.

Same as jQuery’s $(selector).css('property', 'value')

Example which changes the background color of an element:

obj_response.css('#element', 'backgroundColor', 'red')

Note that this can only change a single property at once. It doesn’t support jQuery’s mass change which uses a key/value map of properties/values to change.

Parameters:
  • selector – the jQuery selector to invoke css() on
  • property_name – the name of the style property
  • value – the new value to assign to the property
html(selector, html)

Assigns the given html value to all elements matching the jQuery selector.

Scripts inside the html block are also executed.

Same as jQuery’s: $(selector).html(value)

Example which sets a new html value for an element:

obj_response.html('#element', '<strong>Hey!</strong>')
Parameters:
  • selector – the jQuery selector for which we’ll replace the html
  • html – the html text
html_append(selector, html)

Same as sijax.response.BaseResponse.html(), but appends instead of assigning a new value.

html_prepend(selector, html)

Same as sijax.response.BaseResponse.html(), but prepends instead of assigning a new value.

redirect(uri)

Redirects the browser to the given URI.

Example:

obj_response.redirect('http://example.com/')
remove(selector)

Removes all elements that match the jQuery selector from the DOM.

Example which removes all DIV elements from the page:

obj_response.remove('div')

Same as jQuery’s: $(selector).remove()

script(js)

Executes the given javascript code.

Example:

obj_response.script("alert('Javascript code!');")

Note that the given javascript code is eval-ed inside a Sijax helper function in the browser, so it’s not touching the global namespace, unless you explicitly do it.

StreamingIframeResponse

class sijax.response.StreamingIframeResponse(*args, **kwargs)

A response class used with iframe-calls, that supports streaming.

This class extends sijax.response.BaseResponse and every available method from it works here too.

This is used by plugins that use an iframe to perform the Sijax call, instead of doing a regular ajax request. This has the benefit of allowing us to do streaming, which means that response functions can flush the commands buffer whenever they want without exiting.

To push the current commands to the browser you need to use yield, like this:

def my_func(obj_response):
    obj_response.alert('Doing some work.. wait a second')
    yield obj_response

    from time import sleep
    sleep(5)

    obj_response.alert('Done!')

Your don’t need to explicitly yield at the end of a streaming function. What remains unsent when the function exits will eventually get sent.

Helpers

sijax.helper.init_static_path(static_path)

Mirrors the important static files from the whole Sijax package into a directory of your choice.

It may be a good idea to run this whenever Sijax gets upgraded, so that your files will be kept in sync.

The directory that you provide needs to be empty (if it exists), or to have been previously used by this same function. If the provided directory contains some other files, Sijax will refuse to use it, by raising a sijax.exception.SijaxError exception.

The following files will be made available in the specified directory:

  • sijax.js - the core javascript file used by Sijax

  • json2.js - JSON library that can be loaded for browsers

    that don’t support native JSON (like IE <= 7)

  • sijax_comet.js - the javascript file used by the Comet plugin

  • sijax_upload.js - the javascript file used by the Upload plugin

  • sijax_version - a system file that keeps track of versioning -

    do not touch this file

Exceptions

class sijax.exception.SijaxError

Exception class for Sijax errors.

Comet plugin

sijax.plugin.comet.register_comet_callback(sijax_instance, public_name, callback, **options)

Helps you easily register Comet functions with Sijax.

This is the analogue of sijax.Sijax.register_callback(), but makes the registered function support Comet functionality.

Comet functions need to be called from the browser using:

sjxComet.request('function_name');

instead of the regular:

Sijax.request('function_name');
Parameters:
  • sijax_instance – the sijax.Sijax instance to register callbacks with
  • public_name – the name of the function that the client will use to call it
  • callback – the actual function that would get called to process the request
  • options – options to pass to sijax.Sijax.register_callback()
sijax.plugin.comet.register_comet_object(sijax_instance, obj, **options)

Helps you easily register all “public” callable attributes of an object.

This is the analogue of sijax.Sijax.register_object(), but makes the registered functions support Comet functionality.

Parameters:
class sijax.plugin.comet.CometResponse(*args, **kwargs)

Class used for Comet handler functions, instead of the sijax.response.BaseResponse class.

This class extends sijax.response.BaseResponse and every available method from it works here too.

Also refer to Client side API functions - sjxComet.request() for a way of invoking the Comet Plugin from the browser.

Upload plugin

sijax.plugin.upload.register_upload_callback(sijax_instance, form_id, callback, **options)

Helps you easily register Upload functions with Sijax.

We recommend the args_extra option to be used here, so that the response function would receive the files object or anything else it might be needing to manipulate file uploads. By using args_extra you could change the response function’s default signature from:

def upload_handler(obj_response, form_values)

to:

def upload_handler(obj_response, files, form_values)

where the args_extra=[files] option was passed during registering. To learn more on how the args_extra option works, refer to sijax.Sijax.register_callback().

It’s very important to keep in mind that unlike the regular sijax.Sijax.register_callback() function, this one returns some javascript code as a response. You need to execute that code on the page that contains the form you want to transform to Sijax upload.

Parameters:
  • sijax_instance – the sijax.Sijax instance to register callbacks with
  • form_id – the id of the form as it appears in the DOM
  • callback – the function to call to process the upload request
  • options – options to pass to sijax.Sijax.register_callback()
Returns:

string - javascript code you need to put on your page, to make your form use Sijax when submitted

class sijax.plugin.upload.UploadResponse(*args, **kwargs)

Class used for Upload handler functions, instead of the sijax.response.BaseResponse class.

This class extends sijax.response.BaseResponse and every available method from it works here too.

form_id

The id of the form that was submitted.

You can have several forms handled by the same upload handler function, which can be confusing unless you know the form id.

reset_form()

Resets the form to the state it was in at page loading time.

Any changes made to it after that will be cleared.

Client side API functions - Sijax.request()

You’ve got access to only a handful of functions to use on the client side (in the browser).

The most import and frequently used is Sijax.request(), which makes a new Sijax request to the server.

The signature of Sijax.request() is:

Sijax.request(function_name, [list of arguments], {additional arguments to jQuery.ajax});

The only required argument is the first one - function_name, which specifies which function you want to call.

If no “list of arguments” is specified, the function will be called with no arguments.

The 3rd parameter you can pass to Sijax.request() is the most advanced one, which allows you to override some of the parameters Sijax uses to invoke jQuery.ajax().

Here are several examples:

//Calling a function without arguments
Sijax.request('my_function');

//Calling a function with a single argument
Sijax.request('my_function', ['string argument']);

//Calling a function with 2 arguments
Sijax.request('my_function', ['argument 1', 'argument 2']);

//Calling a function with no arguments, telling the underlying
//jQuery.ajax to use a timeout of 15 seconds
Sijax.request('my_function', [], {"timeout": 15000});

Client side API functions - Sijax.getFormValues()

You often need to submit forms without reloading the page. If you want to use Sijax for that, you would have to extract the fields from the form, create a dictionary and pass that to Sijax.request() (see Client side API functions - Sijax.request()).

Sijax provides a browser helper for that called Sijax.getFormValues() which can extract all the fields from a form on the page and give you a dictionary.

The signature of Sijax.getFormValues() is:

Sijax.getFormValues(jQuery_selector);

The result is a dictionary/object representing the names of the fields in the form matched by the selector and their values.

Here’s some HTML markup and the result of Sijax.getFormValues():

<form id="my_form">
    <input type="text" name="textbox" value="textbox 1" />
    <input type="text" name="tbx[nested]" value="tbx 2" />
    <input type="text" name="textbox2" value="textbox 1" disabled="disabled" />
    <input type="text" value="textbox with no name" />
    <input type="checkbox" name="cbx" checked="checked" />
</form>

<script type="text/javascript">
    var values = Sijax.getFormValues('#my_form');
    /*
    The values variable now contains:
    {
        "textbox": "textbox 1",
        "tbx": {"nested": "tbx 2"},
        "cbx": "on"
    }
    */

    Sijax.request('process_form', [values]);
</script>

In the above example, we’ve used the #my_form jQuery selector to find our form, but any other jQuery selector would work.

You can see that the value for textbox2 was skipped, because the field was disabled. The value for the third text field was also skipped, because the field is missing a name. If the checkbox were unchecked, it would have been skipped too.

Client side API functions - sjxComet.request()

sjxComet.request() is the analogue of Sijax.request() (see Client side API functions - Sijax.request()) for Comet functions (see Comet Plugin).

In order to use this, you’ll need to include the sijax_comet.js file on your page. More on that in Comet Plugin.

sjxComet.request() has the same signature as Sijax.request() except that it has no third parameter to configure jQuery.ajax(), because Comet functions don’t use AJAX requests.

«  Upload Plugin   ::   Contents   ::   Frequently Asked Questions and Notes  »