當前位置: 首頁>>代碼示例>>Python>>正文


Python trafaret.Key方法代碼示例

本文整理匯總了Python中trafaret.Key方法的典型用法代碼示例。如果您正苦於以下問題:Python trafaret.Key方法的具體用法?Python trafaret.Key怎麽用?Python trafaret.Key使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在trafaret的用法示例。


在下文中一共展示了trafaret.Key方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: document_schema

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def document_schema():
    choices = ['a', 'b', 'c']
    schema = t.Dict({
        t.Key('_id'): MongoId,
        t.Key('title'): t.String(max_length=200),
        t.Key('category'): t.String(max_length=200),
        t.Key('body'): t.String,
        t.Key('views'): t.ToInt,
        t.Key('average_note'): t.ToFloat,
        # t.Key('pictures'): t.Dict({}).allow_extra('*'),
        t.Key('published_at'): DateTime,
        # t.Key('tags'): t.List(t.Int),
        t.Key('status'): t.Enum(*choices),
        t.Key('visible'): t.ToBool,
    })
    return schema 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:18,代碼來源:db_fixtures.py

示例2: test_dict

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_dict():
    trafaret = t.Dict({
        t.Key('b'): t.ToInt & check_int,
    })
    res = await trafaret.async_check({'b': '5'})
    assert res == {'b': 5}
    # bad value
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({'b': 'qwe'})
    assert res.value.as_dict() == {'b': "value can't be converted to int"}
    # is not a dict
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check(None)
    assert res.value.as_dict() == "value is not a dict"
    # missed key
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({})
    assert res.value.as_dict() == {'b': 'is required'} 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:20,代碼來源:test_async.py

示例3: test_add_kwargs_ignore

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_add_kwargs_ignore(self):
        first = t.Dict(
            t.Key('bar', trafaret=t.Int()), ignore_extra=['eggs']
        )
        second = t.Dict(
            t.Key('bar1', trafaret=t.Int())
        )
        third = first + second
        third.check({'bar': 4, 'bar1': 41})
        third.check({'bar': 4, 'bar1': 41, 'eggs': 'blabla'})

        first = t.Dict(
            t.Key('bar', trafaret=t.Int()),
        )
        second = t.Dict(
            t.Key('bar1', trafaret=t.Int()), ignore_extra=['eggs']
        )
        third = first + second
        third.check({'bar': 4, 'bar1': 41})
        third.check({'bar': 4, 'bar1': 41, 'eggs': 'blabla'}) 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:22,代碼來源:test_base.py

示例4: test_add_kwargs_extra

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_add_kwargs_extra(self):
        first = t.Dict(
            t.Key('bar', trafaret=t.Int()), allow_extra=['eggs']
        )
        second = t.Dict(t.Key('bar1', trafaret=t.Int()))
        third = first + second
        third.check({"bar": 1, "bar1": 41, "eggs": None})
        third.check({"bar": 1, "bar1": 41})
        with pytest.raises(t.DataError):
            third.check({"bar": 2, "bar1": 1, "marmalade": 5})

        first = t.Dict(t.Key('bar', trafaret=t.Int()))
        second = t.Dict(t.Key('bar1', trafaret=t.Int()), allow_extra=['eggs'])
        third = first + second
        third.check({"bar": 1, "bar1": 41, "eggs": None})
        third.check({"bar": 1, "bar1": 41})
        with pytest.raises(t.DataError):
            third.check({"bar": 2, "bar1": 1, "marmalade": 5}) 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:20,代碼來源:test_base.py

示例5: test_base3

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_base3(self):
        trafaret = t.Dict({t.Key('bar', default=u'nyanya') >> 'baz': t.String}, foo=t.ToInt)
        res = trafaret.check({'foo': 4})
        assert res == {'baz': u'nyanya', 'foo': 4}

        trafaret = trafaret.allow_extra('*')
        res = extract_error(trafaret, {'baz': u'spam', 'foo': 4})
        assert res == {'baz': 'baz key was shadowed'}

        trafaret = trafaret.allow_extra('*', trafaret=t.String)
        res = extract_error(trafaret, {'baaz': 5, 'foo': 4})
        assert res == {'baaz': 'value is not a string'}
        res = trafaret({'baaz': u'strstr', 'foo':4})
        assert res == {'baaz': u'strstr', 'foo':4, 'baz': u'nyanya'}

        trafaret = trafaret.ignore_extra('fooz')
        res = trafaret.check({'foo': 4, 'fooz': 5})
        assert res == {'baz': u'nyanya', 'foo': 4}

        trafaret = trafaret.ignore_extra('*')
        res = trafaret.check({'foo': 4, 'foor': 5})
        assert res == {'baz': u'nyanya', 'foo': 4} 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:24,代碼來源:test_base.py

示例6: test_dict

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_dict(self):
        tt = construct({
            'a': int,
            'b': [str],  # test List
            'c': (str, str, 'atom string'),  # test Tuple
            'f': float,  # test float
            't': Decimal,  # test Type
            t.Key('k'): int,  # test Key
        })
        assert tt({
            'a': 5,
            'b': [u'a'],
            'c': [u'v', u'w', 'atom string'],
            'f': 0.1,
            't': Decimal('100'),
            'k': 100,
        }) == {
                'a': 5,
                'b': ['a'],
                'c': (u'v', u'w', 'atom string'),
                'f': 0.1,
                't': Decimal('100'),
                'k': 100,
        } 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:26,代碼來源:test_constructor.py

示例7: mutate

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def mutate(cls, _, info, __):
        logger.debug("agrs %s", info)
        post_schema = t.Dict({
            'title': t.String(min_length=2),
            'user_id': t.String(min_length=2),
            'content': t.String(min_length=2),
            t.Key('tags',
                  optional=True): t.List(t.String,
                                         min_length=1),
        })

        post_data = post_schema.check(info)
        user_id = post_data.pop('user_id')
        user = User.objects.get_or_404(id=user_id)
        post = Post(author=user, **post_data)
        post.save()
        return cls(post=construct(PostField, post)) 
開發者ID:msoedov,項目名稱:flask-graphql-example,代碼行數:19,代碼來源:ql.py

示例8: generate_keypair

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def generate_keypair():
    logger = Logger({
        'level': 'INFO',
        'drivers': ['console'],
        'pkg-ns': {'ai.backend': 'INFO'},
        'console': {'colored': True, 'format': 'verbose'},
    })
    with logger:
        log.info('generating keypair...')
        ak, sk = _gen_keypair()
        print(f'Access Key: {ak} ({len(ak)} bytes)')
        print(f'Secret Key: {sk} ({len(sk)} bytes)') 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:14,代碼來源:auth.py

示例9: build_key

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def build_key(name, default=_empty):
    if default is not _empty:
        key = t.Key(name, default=default)
    else:
        key = t.Key(name)
    return key 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:8,代碼來源:sa_utils.py

示例10: test_validate_payload

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_validate_payload():
    raw_data = b'{"foo": "bar"}'
    schema = t.Dict({
        t.Key('foo'): t.Atom('bar')
    })
    data = validate_payload(raw_data, schema)
    assert data == {'foo': 'bar'} 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:9,代碼來源:test_utils.py

示例11: test_validate_payload_not_json

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_validate_payload_not_json():
    raw_data = b'foo=bar'
    schema = t.Dict({
        t.Key('foo'): t.Atom('bar')
    })

    with pytest.raises(JsonValidaitonError) as ctx:
        validate_payload(raw_data, schema)

    error = json.loads(ctx.value.text)
    assert error['error'] == 'Payload is not json serialisable' 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:13,代碼來源:test_utils.py

示例12: test_validate_payload_not_valid_schema

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_validate_payload_not_valid_schema():
    raw_data = b'{"baz": "bar"}'
    schema = t.Dict({
        t.Key('foo'): t.Atom('bar')
    })

    with pytest.raises(JsonValidaitonError) as ctx:
        validate_payload(raw_data, schema)

    error = json.loads(ctx.value.text)
    assert error['error'] == 'Invalid json payload' 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:13,代碼來源:test_utils.py

示例13: test_dict_extra_and_ignore

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_dict_extra_and_ignore():
    trafaret = t.Dict(
        t.Key('a', to_name='A', trafaret=t.String),
        allow_extra=['one_extra'],
        allow_extra_trafaret=t.String,
        ignore_extra=['one_ignore'],
    )
    res = await (trafaret.async_check({'a': 's', 'one_extra': 's', 'one_ignore': 's'}))
    assert res == {'A': 's', 'one_extra': 's'}

    # extra key that is not declared in extra not in ignore
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({'a': 's', 'bad_extra': 's'})
    assert res.value.as_dict() == {'bad_extra': 'bad_extra is not allowed key'}

    # extra key that was shadowed
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({'a': 's', 'A': 's'})
    assert res.value.as_dict() == {'A': 'A key was shadowed'}

    # extra key with failed check
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({'a': 's', 'one_extra': 5})
    assert res.value.as_dict() == {'one_extra': 'value is not a string'}

    # shadowing with allow_extra='*'
    trafaret = trafaret.allow_extra('*')
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check({'a': 's', 'A': 's'})
    assert res.value.as_dict() == {'A': 'A key was shadowed'} 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:32,代碼來源:test_async.py

示例14: test_key_with_callable_default

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_key_with_callable_default():
    trafaret = t.Dict(
        t.Key('a', default=lambda: 123, trafaret=t.ToInt),
    )
    res = await trafaret.async_check({})
    assert res == {'a': 123} 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:8,代碼來源:test_async.py

示例15: test_dict_context

# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Key [as 別名]
def test_dict_context(self):
        trafaret = t.Dict({
            t.Key('b'): CONTEXT_TRAFARET,
        })
        assert trafaret({'b': 123}, context=123) == {'b': 123} 
開發者ID:Deepwalker,項目名稱:trafaret,代碼行數:7,代碼來源:test_context.py


注:本文中的trafaret.Key方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。