Fields API#

Fields declare storage for XBlock data. They use abstract notions of scopes to associate each field with particular sets of blocks and users. The hosting runtime application decides what actual storage mechanism to use for each scope.

class xblock.fields.BlockScope#

Enumeration of block scopes.

The block scope specifies how a field relates to blocks. A BlockScope and a UserScope are combined to make a Scope for a field.

USAGE: The data is related to a particular use of a block in a course.

DEFINITION: The data is related to the definition of the block. Although

unusual, one block definition can be used in more than one place in a course.

TYPE: The data is related to all instances of this type of XBlock.

ALL: The data is common to all blocks. This can be useful for storing

information that is purely about the student.

classmethod scopes()#

Return a list of valid/understood class scopes.

class xblock.fields.Boolean(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, **kwargs)#

A field class for representing a boolean.

The value, as loaded or enforced, can be either a Python bool, a string, or any value that will then be converted to a bool in the from_json method.

Examples:

True -> True
'true' -> True
'TRUE' -> True
'any other string' -> False
[] -> False
['123'] -> True
None - > False
enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

class xblock.fields.Dict(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field class for representing a Python dict.

The value, as loaded or enforced, must be either be None or a dict.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

to_string(value)#

In python3, json.dumps() cannot sort keys of different types, so preconvert None to ‘null’.

class xblock.fields.Field(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field class that can be used as a class attribute to define what data the class will want to refer to.

When the class is instantiated, it will be available as an instance attribute of the same name, by proxying through to the field-data service on the containing object.

Parameters:
  • help (str) – documentation for the field, suitable for presenting to a user (defaults to None).

  • default – field’s default value. Can be a static value or the special xblock.fields.UNIQUE_ID reference. When set to xblock.fields.UNIQUE_ID, the field defaults to a unique string that is deterministically calculated for the field in the given scope (defaults to None).

  • scope – this field’s scope (defaults to Scope.content).

  • display_name – the display name for the field, suitable for presenting to a user (defaults to name of the field).

  • values – a specification of the valid values for this field. This can be specified as either a static specification, or a function that returns the specification. For example specification formats, see the values property definition.

  • enforce_type – whether the type of the field value should be enforced on set, using self.enforce_type, raising an exception if it’s not possible to convert it. This provides a guarantee on the stored value type.

  • xml_node – if set, the field will be serialized as a separate node instead of an xml attribute (default: False).

  • force_export – if set, the field value will be exported to XML even if normal export conditions are not met (i.e. the field has no explicit value set)

  • kwargs – optional runtime-specific options/metadata. Will be stored as runtime_options.

property default#

Returns the static value that this defaults to.

delete_from(xblock)#

Delete the value for this field from the supplied xblock

property display_name#

Returns the display name for this class, suitable for use in a GUI.

If no display name has been set, returns the name of the class.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

from_string(serialized)#

Returns a native value from a YAML serialized string representation. Since YAML is a superset of JSON, this is the inverse of to_string.)

is_set_on(xblock)#

Return whether this field has a non-default value on the supplied xblock

property name#

Returns the name of this field.

static needs_name(field)#

Returns whether the given ) is yet to be named.

read_from(xblock)#

Retrieve the value for this field from the specified xblock

read_json(xblock)#

Retrieve the serialized value for this field from the specified xblock

to_json(value)#

Return value in the form of nested lists and dictionaries (suitable for passing to json.dumps).

This is called during field writes to convert the native python type to the value stored in the database

to_string(value)#

Return a JSON serialized string representation of the value.

property values#

Returns the valid values for this class. This is useful for representing possible values in a UI.

Example formats:

  • A finite set of elements:

    [1, 2, 3]
    
  • A finite set of elements where the display names differ from the values:

    [
     {"display_name": "Always", "value": "always"},
     {"display_name": "Past Due", "value": "past_due"},
    ]
    
  • A range for floating point numbers with specific increments:

    {"min": 0 , "max": 10, "step": .1}
    

If this field class does not define a set of valid values, this property will return None.

write_to(xblock, value)#

Set the value for this field to value on the supplied xblock

class xblock.fields.Float(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field that contains a float.

The value, as loaded or enforced, can be None, ‘’ (which will be treated as None), a Python float, or a value that will parse as an float, ie., something for which float(value) does not throw an error.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

class xblock.fields.Integer(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field that contains an integer.

The value, as loaded or enforced, can be None, ‘’ (which will be treated as None), a Python integer, or a value that will parse as an integer, ie., something for which int(value) does not throw an error.

Note that a floating point value will convert to an integer, but a string containing a floating point number (‘3.48’) will throw an error.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

class xblock.fields.List(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field class for representing a list.

The value, as loaded or enforced, can either be None or a list.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

class xblock.fields.Scope(user, block, name=None)#

Defines six types of scopes to be used: content, settings, user_state, preferences, user_info, and user_state_summary.

The content scope is used to save data for all users, for one particular block, across all runs of a course. An example might be an XBlock that wishes to tabulate user “upvotes”, or HTML content to display literally on the page (this example being the reason this scope is named content).

The settings scope is used to save data for all users, for one particular block, for one specific run of a course. This is like the content scope, but scoped to one run of a course. An example might be a due date for a problem.

The user_state scope is used to save data for one user, for one block, for one run of a course. An example might be how many points a user scored on one specific problem.

The preferences scope is used to save data for one user, for all instances of one specific TYPE of block, across the entire platform. An example might be that a user can set their preferred default speed for the video player. This default would apply to all instances of the video player, across the whole platform, but only for that student.

The user_info scope is used to save data for one user, across the entire platform. An example might be a user’s time zone or language preference.

The user_state_summary scope is used to save data aggregated across many users of a single block. For example, a block might store a histogram of the points scored by all users attempting a problem.

Create a new Scope, with an optional name.

classmethod named_scopes()#

Return all named Scopes.

classmethod scopes()#

Return all possible Scopes.

class xblock.fields.ScopeIds(user_id, block_type, def_id, usage_id)#

A simple wrapper to collect all of the ids needed to correctly identify an XBlock (or other classes deriving from ScopedStorageMixin) to a FieldData. These identifiers match up with BlockScope and UserScope attributes, so that, for instance, the def_id identifies scopes that use BlockScope.DEFINITION.

Create new instance of ScopeIds(user_id, block_type, def_id, usage_id)

class xblock.fields.Set(*args, **kwargs)#

A field class for representing a set.

The stored value can either be None or a set.

Set class constructor.

Redefined in order to convert default values to sets.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

class xblock.fields.String(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field class for representing a string.

The value, as loaded or enforced, can either be None or a basestring instance.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

from_json(value)#

Return value as a native full featured python type (the inverse of to_json)

Called during field reads to convert the stored value into a full featured python object

from_string(serialized)#

String gets serialized and deserialized without quote marks.

property none_to_xml#

Returns True to use a XML node for the field and represent None as an attribute.

to_string(value)#

String gets serialized and deserialized without quote marks.

class xblock.fields.UserScope#

Enumeration of user scopes.

The user scope specifies how a field relates to users. A BlockScope and a UserScope are combined to make a Scope for a field.

NONE: Identifies data agnostic to the user of the XBlock. The

data is related to no particular user. All users see the same data. For instance, the definition of a problem.

ONE: Identifies data particular to a single user of the XBlock.

For instance, a student’s answer to a problem.

ALL: Identifies data aggregated while the block is used by many users.

The data is related to all the users. For instance, a count of how many students have answered a question, or a histogram of the answers submitted by all students.

classmethod scopes()#

Return a list of valid/understood class scopes. Why do we need this? I believe it is not used anywhere.

class xblock.fields.XMLString(help=None, default=fields.UNSET, scope=(UserScope.NONE, BlockScope.DEFINITION, 'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)#

A field class for representing an XML string.

The value, as loaded or enforced, can either be None or a basestring instance. If it is a basestring instance, it must be valid XML. If it is not valid XML, an lxml.etree.XMLSyntaxError will be raised.

enforce_type(value)#

Coerce the type of the value, if necessary

Called on field sets to ensure that the stored type is consistent if the field was initialized with enforce_type=True

This must not have side effects, since it will be executed to trigger a DeprecationWarning even if enforce_type is disabled

to_json(value)#

Serialize the data, ensuring that it is valid XML (or None).

Raises an lxml.etree.XMLSyntaxError if it is a basestring but not valid XML.

class xblock.field_data.FieldData#

An interface allowing access to an XBlock’s field values indexed by field names.

default(block, name)#

Get the default value for this field which may depend on context or may just be the field’s global default. The default behavior is to raise KeyError which will cause the caller to return the field’s global default.

Parameters:
  • block (XBlock) – the block containing the field being defaulted

  • name (str) – the field’s name

abstract delete(block, name)#

Reset the value of the field named name to the default for XBlock block.

Parameters:
  • block (XBlock) – block to modify

  • name (str) – field name to delete

abstract get(block, name)#

Retrieve the value for the field named name for the XBlock block.

If no value is set, raise a KeyError.

The value returned may be mutated without modifying the backing store.

Parameters:
  • block (XBlock) – block to inspect

  • name (str) – field name to look up

has(block, name)#

Return whether or not the field named name has a non-default value for the XBlock block.

Parameters:
  • block (XBlock) – block to check

  • name (str) – field name

abstract set(block, name, value)#

Set the value of the field named name for XBlock block.

value may be mutated after this call without affecting the backing store.

Parameters:
  • block (XBlock) – block to modify

  • name (str) – field name to set

  • value – value to set

set_many(block, update_dict)#

Update many fields on an XBlock simultaneously.

Parameters:
  • block (XBlock) – the block to update

  • update_dict (dict) – A map of field names to their new values