How to use the schematics.types.BaseType function in schematics

To help you get started, we’ve selected a few schematics 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 cloudtools / nymms / nymms / schemas / types / __init__.py View on Github external
return json.dumps(value)


StateObject = collections.namedtuple('StateObject', ['name', 'code'])
STATE_OK = StateObject('ok', 0)
STATE_WARNING = STATE_WARN = StateObject('warning', 1)
STATE_CRITICAL = STATE_CRIT = StateObject('critical', 2)
STATE_UNKNOWN = StateObject('unknown', 3)
STATES = collections.OrderedDict([
    ('ok', STATE_OK),
    ('warning', STATE_WARNING),
    ('critical', STATE_CRITICAL),
    ('unknown', STATE_UNKNOWN)])


class StateType(BaseType):
    def __init__(self, *args, **kwargs):
        super(StateType, self).__init__(*args, choices=STATES.values(),
                                        **kwargs)

    def to_native(self, value, context=None):
        if isinstance(value, StateObject):
            return value
        try:
            int_value = int(value)
            try:
                return STATES.values()[int_value]
            except IndexError:
                return STATE_UNKNOWN
        except ValueError:
            try:
                return STATES[value.lower()]
github hotosm / tasking-manager / server / models / dtos / project_dto.py View on Github external
""" Validates Task Creation Mode is known value """
    try:
        TaskCreationMode[value.upper()]
    except KeyError:
        raise ValidationError(
            f"Unknown taskCreationMode: {value} Valid values are {TaskCreationMode.GRID.name}, "
            f"{TaskCreationMode.ARBITRARY.name}"
        )


class DraftProjectDTO(Model):
    """ Describes JSON model used for creating draft project """

    cloneFromProjectId = IntType(serialized_name="cloneFromProjectId")
    project_name = StringType(required=True, serialized_name="projectName")
    area_of_interest = BaseType(required=True, serialized_name="areaOfInterest")
    tasks = BaseType(required=False)
    has_arbitrary_tasks = BooleanType(required=True, serialized_name="arbitraryTasks")
    user_id = IntType(required=True)


class ProjectInfoDTO(Model):
    """ Contains the localized project info"""

    locale = StringType(required=True)
    name = StringType(default="")
    short_description = StringType(serialized_name="shortDescription", default="")
    description = StringType(default="")
    instructions = StringType(default="")
    per_task_instructions = StringType(
        default="", serialized_name="perTaskInstructions"
    )
github hotosm / tasking-manager / server / models / dtos / grid_dto.py View on Github external
from schematics.types import BaseType, BooleanType, IntType, StringType
from schematics import Model


class GridDTO(Model):
    """ Describes JSON model used for creating grids """

    area_of_interest = BaseType(required=True, serialized_name="areaOfInterest")
    grid = BaseType(required=True)
    clip_to_aoi = BooleanType(required=True, serialized_name="clipToAoi")


class SplitTaskDTO(Model):
    """ DTO used to split a task """

    user_id = IntType(required=True)
    task_id = IntType(required=True)
    project_id = IntType(required=True)
    preferred_locale = StringType(default="en")
github hotosm / tasking-manager / server / models / dtos / grid_dto.py View on Github external
from schematics.types import BaseType, BooleanType, IntType, StringType
from schematics import Model


class GridDTO(Model):
    """ Describes JSON model used for creating grids """

    area_of_interest = BaseType(required=True, serialized_name="areaOfInterest")
    grid = BaseType(required=True)
    clip_to_aoi = BooleanType(required=True, serialized_name="clipToAoi")


class SplitTaskDTO(Model):
    """ DTO used to split a task """

    user_id = IntType(required=True)
    task_id = IntType(required=True)
    project_id = IntType(required=True)
    preferred_locale = StringType(default="en")
github PermaData / rill / rill / engine / types.py View on Github external
def is_any(self):
        return type(self.type_def) is schematics.types.BaseType
github cloudtools / nymms / nymms / schemas / types / __init__.py View on Github external
from schematics.exceptions import ValidationError

import arrow


class TimestampType(BaseType):
    def to_native(self, value, context=None):
        if isinstance(value, arrow.arrow.Arrow):
            return value
        return arrow.get(value)

    def to_primitive(self, value, context=None):
        return value.timestamp


class JSONType(BaseType):
    def to_native(self, value, context=None):
        if isinstance(value, basestring):
            return json.loads(value)
        return value

    def to_primitive(self, value, context=None):
        return json.dumps(value)


StateObject = collections.namedtuple('StateObject', ['name', 'code'])
STATE_OK = StateObject('ok', 0)
STATE_WARNING = STATE_WARN = StateObject('warning', 1)
STATE_CRITICAL = STATE_CRIT = StateObject('critical', 2)
STATE_UNKNOWN = StateObject('unknown', 3)
STATES = collections.OrderedDict([
    ('ok', STATE_OK),
github toumorokoshi / transmute-core / transmute_core / object_serializers / cattrs_serializer / converter.py View on Github external
def create_cattrs_converter():
    converter = Converter()
    converter.register_structure_hook(bool, _structure_bool)
    converter.register_structure_hook(string_type, _structure_string)
    converter.register_structure_hook(Model, _structure_schematics)
    converter.register_structure_hook(BaseType, _structure_basetype)
    converter.register_structure_hook(datetime, _structure_datetime)
    converter.register_unstructure_hook(Model, _unstructure_schematics)
    converter.register_unstructure_hook(datetime, _unstructure_datetime)
    converter.register_unstructure_hook(BaseType, _unstructure_basetype)
    return converter
github schematics / schematics / schematics / models.py View on Github external
fields = OrderedDict()
        validator_functions = {}  # Model level
        options_members = {}

        # Accumulate metas info from parent classes
        for base in reversed(bases):
            if hasattr(base, '_schema'):
                fields.update(deepcopy(base._schema.fields))
                options_members.update(dict(base._schema.options))
                validator_functions.update(base._schema.validators)

        # Parse this class's attributes into schema structures
        for key, value in iteritems(attrs):
            if key.startswith('validate_') and isinstance(value, (FunctionType, classmethod)):
                validator_functions[key[9:]] = prepare_validator(value, 4)
            if isinstance(value, BaseType):
                fields[key] = value
            elif isinstance(value, Serializable):
                fields[key] = value

        # Convert declared fields into descriptors for new class
        fields = OrderedDict(sorted(
            (kv for kv in fields.items()),
            key=lambda i: i[1]._position_hint,
        ))
        for key, field in iteritems(fields):
            if isinstance(field, BaseType):
                attrs[key] = FieldDescriptor(key)
            elif isinstance(field, Serializable):
                attrs[key] = field

        klass = type.__new__(mcs, name, bases, attrs)
github loggi / python-choicesenum / choicesenum / schematics / types.py View on Github external
# coding: utf-8
from __future__ import absolute_import, unicode_literals

from choicesenum import ChoicesEnum
from schematics.types import BaseType
from schematics.exceptions import ValidationError


class ChoicesEnumType(BaseType):
    def __init__(self, type_, **kwargs):
        if not issubclass(type_, ChoicesEnum):
            raise ValidationError(self.Messages.INVALID_TYPE)
        super(ChoicesEnumType, self).__init__(type_, kwargs)
        self.type = type_

    def to_native(self, value, context=None):
        return self.type(value)

    def to_primitive(self, value, context=None):
        return self.type(value).value

    class Messages:
        INVALID_TYPE = 'Expected a ChoicesEnum sub type'
github openprocurement / openprocurement.api / src / openprocurement / api / models.py View on Github external
class Address(Model):

    streetAddress = StringType()
    locality = StringType()
    region = StringType()
    postalCode = StringType()
    countryName = StringType(required=True)
    countryName_en = StringType()
    countryName_ru = StringType()


class Location(Model):

    latitude = BaseType(required=True)
    longitude = BaseType(required=True)
    elevation = BaseType()


def validate_dkpp(items, *args):
    if items and not any([i.scheme == u'ДКПП' for i in items]):
        raise ValidationError(u"One of additional classifications should be 'ДКПП'")


class Item(Model):
    """A good, service, or work to be contracted."""

    id = StringType(required=True, min_length=1, default=lambda: uuid4().hex)
    description = StringType(required=True)  # A description of the goods, services to be provided.
    description_en = StringType()
    description_ru = StringType()
    classification = ModelType(CPVClassification, required=True)
    additionalClassifications = ListType(ModelType(Classification), default=list(), required=True, min_size=1, validators=[validate_dkpp])