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 new type of XBlock.

Subclasses of XBlocks can:

  • Name one or more views, i.e. methods which render the block to HTML.

  • Access the parents of their instances.

  • Access and manage the children of their instances.

  • Request services from the runtime, for their instances to use.

  • Define scoped fields, which instances will use to store content, settings, and data.

  • Define how instances are serialized to and deserialized from OLX (Open Learning XML).

  • Mark methods as handlers for AJAX requests.

  • Be installed into a platform as an entry-point plugin.

Note: Don’t override the __init__ method when deriving from this class.

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.

property context_key#

A key identifying the learning context (course, library, etc.) that contains this XBlock-like usage.

Equivalent to .scope_ids.usage_id.context_key.

Returns: * LearningContextKey, if .scope_ids.usage_id is a UsageKey instance. * None, otherwise.

After openedx/XBlock#708 is complete, we can assume that .scope_ids.usage_id is always a UsageKey, and that this method will always return a LearningContextKey.

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.

classmethod get_i18n_js_namespace()#

Gets the JavaScript translations namespace for this XBlock-like class.

Returns:

The JavaScript namespace for this XBlock-like class. None: If this doesn’t have JavaScript translations configured.

Return type:

str

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-like class.

classmethod get_resources_dir()#

Gets the resource directory for this XBlock-like class.

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 a dict containing information that could be used to feed a search index.

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-like 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-like 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-like basis. XBlock-like 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)#

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.

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.

XBlock-like classes declare their service requirements with @XBlock{Aside}.needs and @XBlock{Aside}.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.

property usage_key#

A key identifying this particular usage of the XBlock-like, unique across all learning contexts in the system.

Equivalent to to .scope_ids.usage_id.

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 a XBlock-like 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, *, runtime, **kwargs)#

Base class for XBlock-like objects that are rendered alongside XBlock views.

Subclasses of XBlockAside can:

  • Specify which XBlock views they are to be injected into.

  • Request services from the runtime, for their instances to use.

  • Define scoped fields, which instances will use to store content, settings, and data.

  • Define how instances are serialized to and deserialized from OLX (Open Learning XML).

  • Mark methods as handlers for AJAX requests.

  • Be installed into a platform as an entry-point plugin.

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

  • field_data (FieldData) – Interface used by XBlock-likes’ fields to access their data from wherever it is persisted. DEPRECATED–supply a field-data Runtime service instead.

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

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

property context_key#

A key identifying the learning context (course, library, etc.) that contains this XBlock-like usage.

Equivalent to .scope_ids.usage_id.context_key.

Returns: * LearningContextKey, if .scope_ids.usage_id is a UsageKey instance. * None, otherwise.

After openedx/XBlock#708 is complete, we can assume that .scope_ids.usage_id is always a UsageKey, and that this method will always return a LearningContextKey.

force_save_fields(field_names)#

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

classmethod get_i18n_js_namespace()#

Gets the JavaScript translations namespace for this XBlock-like class.

Returns:

The JavaScript namespace for this XBlock-like class. None: If this doesn’t have JavaScript translations configured.

Return type:

str

classmethod get_public_dir()#

Gets the public directory for this XBlock-like class.

classmethod get_resources_dir()#

Gets the resource directory for this XBlock-like class.

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.

index_dictionary()#

Return a dict containing information that could be used to feed a search index.

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 needs(*service_names)#

A class decorator to indicate that an XBlock-like 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-like 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-like basis. XBlock-like 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)#

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.

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.

XBlock-like classes declare their service requirements with @XBlock{Aside}.needs and @XBlock{Aside}.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.

property usage_key#

A key identifying this particular usage of the XBlock-like, unique across all learning contexts in the system.

Equivalent to to .scope_ids.usage_id.

classmethod wants(*service_names)#

A class decorator to indicate that a XBlock-like 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?