How to use the xblock.fields.JSONField function in XBlock

To help you get started, we’ve selected a few XBlock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github edx / XBlock / xblock / fields.py View on Github external
def _warn_deprecated_outside_JSONField(self):  # pylint: disable=invalid-name
        """Certain methods will be moved to JSONField.

        This warning marks calls when the object is not
        derived from that class.
        """
        if not isinstance(self, JSONField) and not self.warned:
            warnings.warn(
                "Deprecated. JSONifiable fields should derive from JSONField ({name})".format(name=self.name),
                DeprecationWarning,
                stacklevel=3
            )
            self.warned = True
github edx / XBlock / xblock / fields.py View on Github external
return self.from_json(value)


class Any(JSONField):
    """
    A field class for representing any piece of data; type is not enforced.

    All methods are inherited directly from `Field`.

    THIS SHOULD BE DEPRECATED. THIS SHOULD EITHER BE ANY JSON DATA, OR IT MAKES NO SENSE
    """
    pass


class Reference(JSONField):
    """
    An xblock reference. That is, a pointer to another xblock.

    It's up to the runtime to know how to dereference this field type, but the field type enables the
    runtime to know that it must do the interpretation.
    """
    pass


class ReferenceList(List):
    """
    An list of xblock references. That is, pointers to xblocks.

    It's up to the runtime to know how to dereference the elements of the list. The field type enables the
    runtime to know that it must do the interpretation.
    """
github appsembler / xblock-video / video_xblock / fields.py View on Github external
"""
RelativeTive field back-ported from xmodule.fields.

Backported to reduce coupling with XModule and make linting & testing possible.
Reference:
https://github.com/edx/edx-platform/blob/open-release/eucalyptus.master/common/lib/xmodule/xmodule/fields.py#L143
"""

import datetime
import time

from xblock.fields import JSONField


class RelativeTime(JSONField):
    """
    Field for start_time and end_time video module properties.

    It was decided, that python representation of start_time and end_time
    should be python datetime.timedelta object, to be consistent with
    common time representation.

    At the same time, serialized representation should be "HH:MM:SS"
    This format is convenient to use in XML (and it is used now),
    and also it is used in frond-end studio editor of video module as format
    for start and end time fields.

    In database we previously had float type for start_time and end_time fields,
    so we are checking it also.

    Python object of RelativeTime is datetime.timedelta.
github edx / XBlock / xblock / fields.py View on Github external
def __init__(self, help=None, default=UNSET, scope=Scope.content, display_name=None, **kwargs):  # pylint: disable=redefined-builtin
        super(Boolean, self).__init__(help, default, scope, display_name,
                                      values=({'display_name': "True", "value": True},
                                              {'display_name': "False", "value": False}),
                                      **kwargs)

    def from_json(self, value):
        if isinstance(value, basestring):
            return value.lower() == 'true'
        else:
            return bool(value)

    enforce_type = from_json


class Dict(JSONField):
    """
    A field class for representing a Python dict.

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

    """
    _default = {}

    def from_json(self, value):
        if value is None or isinstance(value, dict):
            return value
        else:
            raise TypeError('Value stored in a Dict must be None or a dict, found %s' % type(value))

    enforce_type = from_json
github edx / XBlock / xblock / fields.py View on Github external
The value, as loaded or enforced, must be either be None or a dict.

    """
    _default = {}

    def from_json(self, value):
        if value is None or isinstance(value, dict):
            return value
        else:
            raise TypeError('Value stored in a Dict must be None or a dict, found %s' % type(value))

    enforce_type = from_json


class List(JSONField):
    """
    A field class for representing a list.

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

    """
    _default = []

    def from_json(self, value):
        if value is None or isinstance(value, list):
            return value
        else:
            raise TypeError('Value stored in a List must be None or a list, found %s' % type(value))

    enforce_type = from_json
github edx / XBlock / xblock / fields.py View on Github external
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.

    """
    MUTABLE = False

    def from_json(self, value):
        if value is None or value == '':
            return None
        return int(value)

    enforce_type = from_json


class Float(JSONField):
    """
    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.

    """
    MUTABLE = False

    def from_json(self, value):
        if value is None or value == '':
            return None
        return float(value)

    enforce_type = from_json
github edx / XBlock / xblock / fields.py View on Github external
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.

    """
    MUTABLE = False

    def from_json(self, value):
        if value is None or value == '':
            return None
        return float(value)

    enforce_type = from_json


class Boolean(JSONField):
    """
    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
github edx / XBlock / xblock / fields.py View on Github external
Serialize the date as an ISO-formatted date string, or None.
        """
        if isinstance(value, datetime.datetime):
            return value.strftime(self.DATETIME_FORMAT)
        if value is None:
            return None
        raise TypeError("Value stored must be a datetime object, not {}".format(type(value)))

    def enforce_type(self, value):
        if isinstance(value, datetime.datetime) or value is None:
            return value

        return self.from_json(value)


class Any(JSONField):
    """
    A field class for representing any piece of data; type is not enforced.

    All methods are inherited directly from `Field`.

    THIS SHOULD BE DEPRECATED. THIS SHOULD EITHER BE ANY JSON DATA, OR IT MAKES NO SENSE
    """
    pass


class Reference(JSONField):
    """
    An xblock reference. That is, a pointer to another xblock.

    It's up to the runtime to know how to dereference this field type, but the field type enables the
    runtime to know that it must do the interpretation.
github edx / XBlock / xblock / fields.py View on Github external
"""
        # pylint: disable=protected-access
        return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name)

    def __hash__(self):
        return hash(self.name)


class JSONField(Field):
    """
    Field type which has a convenient JSON representation.
    """
    pass  # for now; we'll bubble functions down when we finish deprecation in Field


class Integer(JSONField):
    """
    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.

    """
    MUTABLE = False

    def from_json(self, value):
        if value is None or value == '':
            return None
github edx / XBlock / xblock / fields.py View on Github external
return value
        else:
            raise TypeError('Value stored in a String must be None or a string, found %s' % type(value))

    def from_string(self, value):
        """String gets serialized and deserialized without quote marks."""
        return self.from_json(value)

    def to_string(self, value):
        """String gets serialized and deserialized without quote marks."""
        return self.to_json(value)

    enforce_type = from_json


class DateTime(JSONField):
    """
    A field for representing a datetime.

    The value, as loaded or enforced, can either be an ISO-formatted date string, a native datetime,
    or None.
    """

    DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'

    def from_json(self, value):
        """
        Parse the date from an ISO-formatted date string, or None.
        """
        if isinstance(value, basestring):

            # Parser interprets empty string as now by default