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.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.Scope

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 ti 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

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.Field(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.
default

Returns the static value that this defaults to.

delete_from(xblock)

Delete the value for this field from the supplied xblock

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

name

Returns the name of this field.

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.

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.Boolean(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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
class xblock.fields.Dict(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

to_string(value)

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

class xblock.fields.Float(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

class xblock.fields.Integer(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

class xblock.fields.List(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

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.

class xblock.fields.String(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

from_string(value)

String gets serialized and deserialized without quote marks.

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.XMLString(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'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.

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.fields.XBlockMixin(*args, **kwargs)

A wrapper around xblock.core.XBlockMixin that provides backwards compatibility for the old location.

Deprecated.

class xblock.reference.plugins.Filesystem(help=None, default=fields.UNSET, scope=ScopeBase(user=UserScope.NONE, block=BlockScope.DEFINITION, name=u'content'), display_name=None, values=None, enforce_type=False, xml_node=False, force_export=False, **kwargs)

An enhanced pyfilesystem.

This returns a file system provided by the runtime. The file system has two additional methods over a normal pyfilesytem:

  • get_url allows it to return a URL for a file
  • expire allows it to create files which may be garbage collected after a preset period. edx-platform and xblock-sdk do not currently garbage collect them, however.

More information can be found at: http://docs.pyfilesystem.org/en/latest/ and https://github.com/pmitros/django-pyfs

The major use cases for this are storage of large binary objects, pregenerating per-student data (e.g. pylab plots), and storing data which should be downloadable (for example, serving <img src=…> will typically be faster through this than serving that up through XBlocks views.