XBlock API

class xblock.core.XBlock(runtime, field_data=None, scope_ids=<object object>, *args, **kwargs)

Base class for XBlocks.

Derive from this class to create a new kind of XBlock. There are no required methods, but you will probably need at least one view.

Don’t provide the __init__ method when deriving from this class.

Construct a new XBlock.

This class should only be instantiated by runtimes.

Parameters
  • runtime (Runtime) – Use it to access the environment. It is available in XBlock code as self.runtime.

  • field_data (FieldData) – Interface used by the XBlock fields to access their data from wherever it is persisted. Deprecated.

  • scope_ids (ScopeIds) – Identifiers needed to resolve scopes.

add_children_to_node(node)

Add children to etree.Element node.

add_xml_to_node(node)

For exporting, set data on etree.Element node.

clear_child_cache()

Reset the cache of children stored on this XBlock.

force_save_fields(field_names)

Save all fields that are specified in field_names, even if they are not dirty.

get_child(usage_id)

Return the child identified by usage_id.

get_children(usage_id_filter=None)

Return instantiated XBlocks for each of this blocks children.

get_parent()

Return the parent block of this block, or None if there isn’t one.

classmethod get_public_dir()

Gets the public directory for this XBlock.

classmethod get_resources_dir()

Gets the resource directory for this XBlock.

handle(handler_name, request, suffix='')

Handle request with this block’s runtime.

classmethod handler(func)

A decorator to indicate a function is usable as a handler.

The wrapped function must return a webob.Response object.

property has_cached_parent

Return whether this block has a cached parent block.

has_support(view, functionality)

Returns whether the given view has support for the given functionality.

An XBlock view declares support for a functionality with the @XBlock.supports decorator. The decorator stores information on the view.

Note: We implement this as an instance method to allow xBlocks to override it, if necessary.

Parameters
  • view (object) – The view of the xBlock.

  • functionality (str) – A functionality of the view. For example: “multi_device”.

Returns

True or False

index_dictionary()

return key/value fields to feed an index within in a Python dict object values may be numeric / string or dict

classmethod json_handler(func)

Wrap a handler to consume and produce JSON.

Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response.

The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code.

This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON.

classmethod load_class(identifier, default=None, select=None)

Load a single class specified by identifier.

If identifier specifies more than a single class, and select is not None, then call select on the list of entry_points. Otherwise, choose the first one and log a warning.

If default is provided, return it if no entry_point matching identifier is found. Otherwise, will raise a PluginMissingError

If select is provided, it should be a callable of the form:

def select(identifier, all_entry_points):
    # ...
    return an_entry_point

The all_entry_points argument will be a list of all entry_points matching identifier that were found, and select should return one of those entry_points to be loaded. select should raise PluginMissingError if no plugin is found, or AmbiguousPluginError if too many plugins are found

classmethod load_classes(fail_silently=True)

Load all the classes for a plugin.

Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin.

fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is disagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.

classmethod load_tagged_classes(tag, fail_silently=True)

Produce a sequence of all XBlock classes tagged with tag.

fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is diagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.

classmethod needs(*service_names)

A class decorator to indicate that an XBlock class needs particular services.

classmethod open_local_resource(uri)

Open a local resource.

The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and return an open file-like object for the resource.

For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to “public”. The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource.

classmethod parse_xml(node, runtime, keys, id_generator)

Use node to construct a new block.

Parameters
  • node (Element) – The xml node to parse into an xblock.

  • runtime (Runtime) – The runtime to use while parsing.

  • keys (ScopeIds) – The keys identifying where this block will store its data.

  • id_generator (IdGenerator) – An object that will allow the runtime to generate correct definition and usage ids for children of this block.

classmethod register_temp_plugin(class_, identifier=None, dist='xblock')

Decorate a function to run with a temporary plugin available.

Use it like this in tests:

@register_temp_plugin(MyXBlockClass):
def test_the_thing():
    # Here I can load MyXBlockClass by name.
render(view, context=None)

Render view with this block’s runtime and the supplied context

save()

Save all dirty fields attached to this XBlock.

classmethod service_declaration(service_name)

Find and return a service declaration.

XBlocks declare their service requirements with @XBlock.needs and @XBlock.wants decorators. These store information on the class. This function finds those declarations for a block.

Parameters

service_name (str) – the name of the service requested.

Returns

One of “need”, “want”, or None.

classmethod supports(*functionalities)

A view decorator to indicate that an xBlock view has support for the given functionalities.

Parameters

functionalities – String identifiers for the functionalities of the view. For example: “multi_device”.

static tag(tags)

Returns a function that adds the words in tags as class tags to this class.

ugettext(text)

Translates message/text and returns it in a unicode string. Using runtime to get i18n service.

validate()

Ask this xblock to validate itself. Subclasses are expected to override this method, as there is currently only a no-op implementation. Any overriding method should call super to collect validation results from its superclasses, and then add any additional results as necessary.

classmethod wants(*service_names)

A class decorator to indicate that an XBlock class wants particular services.

xml_element_name()

What XML element name should be used for this block?

xml_text_content()

What is the text content for this block’s XML node?

class xblock.core.XBlockAside(scope_ids, field_data=None, **kwargs)

This mixin allows Xblock-like class to declare that it provides aside functionality.

Parameters
  • field_data (FieldData) – Interface used by the XBlock fields to access their data from wherever it is persisted.

  • scope_ids (ScopeIds) – Identifiers needed to resolve scopes.

add_xml_to_node(node)

For exporting, set data on node from ourselves.

classmethod aside_for(view_name)

A decorator to indicate a function is the aside view for the given view_name.

Aside views should have a signature like:

@XBlockAside.aside_for('student_view')
def student_aside(self, block, context=None):
    ...
    return Fragment(...)
aside_view_declaration(view_name)

Find and return a function object if one is an aside_view for the given view_name

Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block.

Parameters

view_name (str) – the name of the view requested.

Returns

either the function or None

force_save_fields(field_names)

Save all fields that are specified in field_names, even if they are not dirty.

classmethod get_public_dir()

Gets the public directory for this XBlock.

classmethod get_resources_dir()

Gets the resource directory for this XBlock.

handle(handler_name, request, suffix='')

Handle request with this block’s runtime.

classmethod handler(func)

A decorator to indicate a function is usable as a handler.

The wrapped function must return a webob.Response object.

classmethod json_handler(func)

Wrap a handler to consume and produce JSON.

Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response.

The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code.

This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON.

classmethod load_class(identifier, default=None, select=None)

Load a single class specified by identifier.

If identifier specifies more than a single class, and select is not None, then call select on the list of entry_points. Otherwise, choose the first one and log a warning.

If default is provided, return it if no entry_point matching identifier is found. Otherwise, will raise a PluginMissingError

If select is provided, it should be a callable of the form:

def select(identifier, all_entry_points):
    # ...
    return an_entry_point

The all_entry_points argument will be a list of all entry_points matching identifier that were found, and select should return one of those entry_points to be loaded. select should raise PluginMissingError if no plugin is found, or AmbiguousPluginError if too many plugins are found

classmethod load_classes(fail_silently=True)

Load all the classes for a plugin.

Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin.

fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is disagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.

classmethod needs(*service_names)

A class decorator to indicate that an XBlock class needs particular services.

needs_serialization()

Return True if the aside has any data to serialize to XML.

If all of the aside’s data is empty or a default value, then the aside shouldn’t be serialized as XML at all.

classmethod open_local_resource(uri)

Open a local resource.

The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back to this method. The XBlock must parse this URI and return an open file-like object for the resource.

For security reasons, the default implementation will return only a very restricted set of file types, which must be located in a folder that defaults to “public”. The location used for public resources can be changed on a per-XBlock basis. XBlock authors who want to override this behavior will need to take care to ensure that the method only serves legitimate public resources. At the least, the URI should be matched against a whitelist regex to ensure that you do not serve an unauthorized resource.

classmethod parse_xml(node, runtime, keys, id_generator)

Use node to construct a new block.

Parameters
  • node (Element) – The xml node to parse into an xblock.

  • runtime (Runtime) – The runtime to use while parsing.

  • keys (ScopeIds) – The keys identifying where this block will store its data.

  • id_generator (IdGenerator) – An object that will allow the runtime to generate correct definition and usage ids for children of this block.

classmethod register_temp_plugin(class_, identifier=None, dist='xblock')

Decorate a function to run with a temporary plugin available.

Use it like this in tests:

@register_temp_plugin(MyXBlockClass):
def test_the_thing():
    # Here I can load MyXBlockClass by name.
save()

Save all dirty fields attached to this XBlock.

classmethod service_declaration(service_name)

Find and return a service declaration.

XBlocks declare their service requirements with @XBlock.needs and @XBlock.wants decorators. These store information on the class. This function finds those declarations for a block.

Parameters

service_name (str) – the name of the service requested.

Returns

One of “need”, “want”, or None.

classmethod should_apply_to_block(block)

Return True if the aside should be applied to a given block. This can be overridden if some aside should only wrap blocks with certain properties.

classmethod wants(*service_names)

A class decorator to indicate that an XBlock class wants particular services.

xml_element_name()

What XML element name should be used for this block?

xml_text_content()

What is the text content for this block’s XML node?