How to use the schematics.types.compound.DictType 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_dict_type.py View on Github external
def test_dict_type_with_model_type():
    class CategoryStats(Model):
        category_slug = StringType()
        total_wins = IntType()

    class PlayerInfo(Model):
        categories = DictType(ModelType(CategoryStats))
        #TODO: Maybe it would be cleaner to have
        #       DictType(CategoryStats) and implicitly convert to ModelType(CategoryStats)

    info = PlayerInfo(dict(categories={
        "math": {
            "category_slug": "math",
            "total_wins": 1
        },
        "batman": {
            "category_slug": "batman",
            "total_wins": 3
        }
    }))

    math_stats = CategoryStats({"category_slug": "math", "total_wins": 1})
    assert info.categories["math"] == math_stats
github schematics / schematics / tests / test_serialize.py View on Github external
def test_field_with_serialize_when_none_on_outer_only():
    class M(Model):
        listfield = ListType(StringType(serialize_when_none=True), serialize_when_none=False)
        dictfield = DictType(StringType(serialize_when_none=True), serialize_when_none=False)
    obj = M()
    obj.listfield = [None]
    obj.dictfield = {'foo': None}
    assert obj.serialize() == {'listfield': [None], 'dictfield': {'foo': None}}
github schematics / schematics / tests / test_serialize.py View on Github external
return cls(dict(level=total_points * 2, stars=total_points))

    class CategoryStatsInfo(Model):
        category_slug = StringType()
        total_points = IntType(default=0)

        @serializable(type=ModelType(ExperienceLevel))
        def xp_level(self):
            return ExperienceLevel.from_total_points(self.total_points, self.category_slug)

    class PlayerInfo(Model):
        id = LongType()
        display_name = StringType()

    class PlayerCategoryInfo(PlayerInfo):
        categories = DictType(ModelType(CategoryStatsInfo))

    info = PlayerCategoryInfo(dict(
        id="1",
        display_name="John Doe",
        categories={
            "math": {
                "category_slug": "math",
                "total_points": 1
            }
        }
    ))

    assert info.categories["math"].xp_level.level == 2
    assert info.categories["math"].xp_level.stars == 1

    d = info.serialize()
github scrapinghub / spidermon / tests / test_validators_schematics.py View on Github external
def test_dict():
    """
    messages:
        - INVALID_DICT
        - INVALID_INT
    """

    class Data(Model):
        a = DictType(field=IntType)

    INVALID = ["a", Data]
    VALID = [{}, {"some": 1}]
    if SCHEMATICS1:
        VALID.append([])
    else:
        INVALID.append([])
    _test_valid_invalid(
        model=Data, valid=VALID, invalid=INVALID, expected_error=messages.INVALID_DICT
    )
    if SCHEMATICS1:
        _test_data(
            model=Data,
            data={"a": {"some": "a"}},
            expected=(False, {"a": [messages.INVALID_INT]}),
        )
github schematics / schematics / tests / test_flatten.py View on Github external
def test_flatten_with_dicttype_model_types():
    class CategoryStats(Model):
        total_wins = IntType()

    class PlayerCategoryInfo(Model):
        id = StringType(required=True)
        categories = DictType(ModelType(CategoryStats), required=True)

    p = PlayerCategoryInfo(dict(
        id="1",
        categories={
            "a": {"total_wins": 1},
            "b": {"total_wins": 5},
        }
    ))
    flat = p.flatten()

    assert flat == {
        "id": "1",
        "categories.a.total_wins": 1,
        "categories.b.total_wins": 5,
    }
github hotosm / tasking-manager / server / models / dtos / task_annotation_dto.py View on Github external
from schematics import Model
from schematics.types import StringType, IntType
from schematics.types.compound import DictType


class TaskAnnotationDTO(Model):
    """ Model for a single task annotation """

    task_id = IntType(required=True, serialized_name="taskId")
    annotation_type = StringType(required=True, serialized_name="annotationType")
    annotation_source = StringType(serialized_name="annotationSource")
    annotation_markdown = StringType(serialized_name="annotationMarkdown")
    properties = DictType(StringType, serialized_name="properties")
github st4lk / acl_webapp / acl_webapp / news / models.py View on Github external
# -*- coding: utf-8 -*-
from schematics.types import StringType
from schematics.types.compound import ListType, DictType
from base.models import BaseModel


class NewsModel(BaseModel):
    title = StringType()
    content = StringType()
    author = StringType()  # email of author
    comments = ListType(DictType, compound_field=StringType)

    MONGO_COLLECTION = 'news'
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.
github toumorokoshi / transmute-core / transmute_core / object_serializers / schematics_serializer.py View on Github external
def _to_json_schema_no_cache(model):
    if isinstance(model, ModelType):
        return _model_type_to_json_schema(model)
    elif isinstance(model, ListType):
        return _list_type_to_json_schema(model)
    elif isinstance(model, DictType):
        return _dict_type_to_json_schema(model)
    else:
        for cls, schema in JSON_SCHEMA_MAP.items():
            if isinstance(model, cls):
                return schema
    if isinstance(model, BaseType):
        return {"type": "object"}
    if isinstance(model, Serializable):
        return _to_json_schema_no_cache(model.type)
    raise SerializationException(
        "unable to create json schema for type "
        + "{0}. Expected a primitive or ".format(model)
        + " a schematics model or type"
    )
github jmcarp / betfair.py / betfair / models.py View on Github external
placed_date = DateTimeType()
    selection_id = LongType()
    selection_name = StringType()
    start_date = DateTimeType()
    transaction_type = StringType()
    transaction_id = LongType()
    win_lose = StringType()


class StatementItem(BetfairModel):
    ref_id = StringType()
    item_date = DateTimeType()
    amount = FloatType()
    balance = FloatType()
    item_class = EnumType(constants.ItemClass)
    item_class_data = DictType(StringType)
    legacy_data = ModelType(StatementLegacyData)


class AccountDetailsResponse(BetfairModel):
    currency_code = StringType()
    first_name = StringType()
    last_name = StringType()
    locale_code = StringType()
    region = StringType()
    timezone = StringType()
    discount_rate = FloatType()
    points_balance = IntType()
    country_code = StringType()


class AccountStatementReport(BetfairModel):