How to use the schematics.types.compound.ListType 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 schematics / schematics / tests / test_list_type.py View on Github external
def test_list_model_field_exception_with_full_message():
    class User(Model):
        name = StringType(max_length=1)

    class Group(Model):
        users = ListType(ModelType(User))

    g = Group({'users': [{'name': "ToLongName"}]})

    with pytest.raises(DataError) as exception:
        g.validate()
    assert exception.value.messages == {'users': {0: {'name': ['String value is too long.']}}}
github schematics / schematics / tests / fixtures.py View on Github external
value = StringType(required=True, max_length=256)
    tags = ListType(StringType())


class SingleTask(Model):
    """A `SingleTask` associates a creation date with an `Action` instance.
    """
    action = ModelType(Action)
    created_date = DateTimeType(default=datetime.datetime.now)


class TaskList(Model):
    """A `TaskList` associated a creation date and updated_date with a list of
    `Action` instances.
    """
    actions = ListType(ModelType(Action))
    created_date = DateTimeType(default=datetime.datetime.now)
    updated_date = DateTimeType(default=datetime.datetime.now)
    num_completed = IntType(default=0)


#
# Actions
#

a1 = Action(value='Hello Mike', tags=['Erlang', 'Mike Williams'])
a2 = Action(value='Hello Joe', tags=['Erlang', 'Joe Armstrong'])


#
# SingleTask
#
github schematics / schematics / tests / fixtures.py View on Github external
trust fund keffiyeh dreamcatcher skateboard, williamsburg yr salvia tattooed
"""

blogpost = BlogPost(title='Hipster Hodgepodge', author=author, content=content,
                    comments=[comment1, comment2], deleted=False)


#
# Models
#

class Action(Model):
    """An `Action` associates an action name with a list of tags.
    """
    value = StringType(required=True, max_length=256)
    tags = ListType(StringType())


class SingleTask(Model):
    """A `SingleTask` associates a creation date with an `Action` instance.
    """
    action = ModelType(Action)
    created_date = DateTimeType(default=datetime.datetime.now)


class TaskList(Model):
    """A `TaskList` associated a creation date and updated_date with a list of
    `Action` instances.
    """
    actions = ListType(ModelType(Action))
    created_date = DateTimeType(default=datetime.datetime.now)
    updated_date = DateTimeType(default=datetime.datetime.now)
github predicthq / sdk-py / predicthq / endpoints / schemas.py View on Github external
def export_format(self):  # pragma: nocover
        raise NotImplementedError()

    def convert(self, raw_data, **kw):
        if isinstance(raw_data, six.string_types):
            try:
                raw_data = re.match(self.import_format, six.text_type(raw_data)).groupdict()
            except AttributeError:
                raise SchematicsValidationError("'{}' is not a valid format for {}".format(raw_data, self.__class__.__name__))
        return super(StringModel, self).convert(raw_data, **kw)

    def export(self, *args, **kwargs):
        return self.export_format.format(**super(StringModel, self).export(*args, **kwargs))


class StringListType(SchematicsListType):

    def __init__(self, field, separator=" ", **kwargs):
        self.separator = separator
        super(StringListType, self).__init__(field, **kwargs)

    def _coerce(self, value):
        if isinstance(value, six.string_types):
            return value.split(self.separator)
        elif isinstance(value, dict):
            return [value]
        else:
            return super(StringListType, self)._coerce(value)

    def _export(self, *args, **kwargs):
        data = super(StringListType, self)._export(*args, **kwargs)
        return self.separator.join(map(six.text_type, data))
github aldanor / pynab / ynab / schema.py View on Github external
name = StringType()
    sortableIndex = IntType()
    type = StringType()


class SubCategory(Category):
    cachedBalance = FloatType()
    masterCategoryId = StringType()
    isResolvedConflict = BooleanType()
    note = StringType()


class MasterCategory(Category):
    deleteable = BooleanType()
    expanded = BooleanType()
    subCategories = ListType(ModelType(SubCategory))


class Account(DeletableEntity):
    accountName = StringType()
    accountType = StringType()
    hidden = BooleanType()
    onBudget = BooleanType()
    lastReconciledDate = DateType()
    lastReconciledBalance = FloatType()
    lastEnteredCheckNumber = FloatType()
    sortableIndex = IntType()
    note = StringType()


class PayeeLocation(DeletableEntity):
    parentPayeeId = StringType()
github openprocurement / openprocurement.api / src / openprocurement / api / models / common.py View on Github external
class Revision(Model):
    author = StringType()
    date = IsoDateTimeType(default=get_now)
    changes = ListType(DictType(BaseType), default=list())
    rev = StringType()


class BaseResourceItem(SchematicsDocument, Model):
    owner = StringType()  # the broker
    owner_token = StringType()  # token for broker access
    transfer_token = SHA512Type()  # token wich allows you to change the broker
    mode = StringType(choices=['test'])  # need for switching auction to different states
    dateModified = IsoDateTimeType()
    _attachments = DictType(DictType(BaseType), default=dict())  # couchdb attachments
    revisions = ListType(ModelType(Revision), default=list())  # couchdb rev

    __name__ = ''

    def __repr__(self):
        return '<%s:%r@%r>' % (type(self).__name__, self.id, self.rev)

    @serializable(serialized_name='id')
    def doc_id(self):
        """A property that is serialized by schematics exports."""
        return self._id

    def import_data(self, raw_data, **kw):
        """
        Converts and imports the raw data into the instance of the model
        according to the fields in the model.
        :param raw_data:
github hotosm / tasking-manager / server / models / dtos / project_dto.py View on Github external
def __init__(self):
        super().__init__()
        self.favorited_projects = []

    favorited_projects = ListType(
        ModelType(ProjectDTO), serialized_name="favoritedProjects"
    )


class ProjectSearchDTO(Model):
    """ Describes the criteria users use to filter active projects"""

    preferred_locale = StringType(default="en")
    mapper_level = StringType(validators=[is_known_mapping_level])
    mapping_types = ListType(StringType, validators=[is_known_mapping_type])
    project_statuses = ListType(StringType, validators=[is_known_project_status])
    organisation_name = StringType()
    organisation_id = IntType()
    team_id = IntType()
    campaign = StringType()
    order_by = StringType(choices=ORDER_BY_OPTIONS)
    order_by_type = StringType(choices=("ASC", "DESC"))
    country = StringType()
    page = IntType(required=True)
    text_search = StringType()
    is_project_manager = BooleanType(required=True, default=False)
    mapping_editors = ListType(StringType, validators=[is_known_editor])
    validation_editors = ListType(StringType, validators=[is_known_editor])
    teams = ListType(StringType())
    interests = ListType(IntType())
    created_by = IntType(required=False)
github hotosm / tasking-manager / server / models / dtos / validator_dto.py View on Github external
class UnlockAfterValidationDTO(Model):
    """ DTO used to transmit the status of multiple tasks after validation """

    project_id = IntType(required=True)
    validated_tasks = ListType(
        ModelType(ValidatedTask), required=True, serialized_name="validatedTasks"
    )
    user_id = IntType(required=True)
    preferred_locale = StringType(default="en")


class StopValidationDTO(Model):
    """ DTO used to transmit the the request to stop validating multiple tasks """

    project_id = IntType(required=True)
    reset_tasks = ListType(
        ModelType(ResetValidatingTask), required=True, serialized_name="resetTasks"
    )
    user_id = IntType(required=True)
    preferred_locale = StringType(default="en")


class MappedTasksByUser(Model):
    """ Describes number of tasks user has mapped on a project"""

    username = StringType(required=True)
    mapped_task_count = IntType(required=True, serialized_name="mappedTaskCount")
    tasks_mapped = ListType(IntType, required=True, serialized_name="tasksMapped")
    last_seen = DateTimeType(required=True, serialized_name="lastSeen")
    mapping_level = StringType(required=True, serialized_name="mappingLevel")
    date_registered = DateTimeType(serialized_name="dateRegistered")
    last_validation_date = DateTimeType(serialized_name="lastValidationDate")
github hotosm / tasking-manager / server / models / dtos / user_dto.py View on Github external
pagination = ModelType(Pagination)
    users = ListType(ModelType(ListedUser))


class UserFilterDTO(Model):
    """ DTO to hold all Tasking Manager users """

    def __init__(self):
        super().__init__()
        self.usernames = []
        self.users = []

    pagination = ModelType(Pagination)
    usernames = ListType(StringType)
    users = ListType(ModelType(ProjectParticipantUser))
github hotosm / tasking-manager / server / models / dtos / project_dto.py View on Github external
serialized_name="validationEditors",
        validators=[is_known_editor],
    )


class PMDashboardDTO(Model):
    """ DTO for constructing the PM Dashboard """

    def __init__(self):
        """ DTO constructor initialise all arrays to empty"""
        super().__init__()
        self.draft_projects = []
        self.archived_projects = []
        self.active_projects = []

    draft_projects = ListType(
        ModelType(ProjectSummary), serialized_name="draftProjects"
    )
    active_projects = ListType(
        ModelType(ProjectSummary), serialized_name="activeProjects"
    )
    archived_projects = ListType(
        ModelType(ProjectSummary), serialized_name="archivedProjects"
    )


class ProjectTaskAnnotationsDTO(Model):
    """ DTO for task annotations of a project """

    def __init__(self):
        """ DTO constructor set task arrays to empty """
        super().__init__()