当前位置: 首页>>代码示例>>Python>>正文


Python trafaret.Dict方法代码示例

本文整理汇总了Python中trafaret.Dict方法的典型用法代码示例。如果您正苦于以下问题:Python trafaret.Dict方法的具体用法?Python trafaret.Dict怎么用?Python trafaret.Dict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在trafaret的用法示例。


在下文中一共展示了trafaret.Dict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: build_field

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def build_field(key, value, relations=None):
    extra = None
    name = key
    if isinstance(value, t.ToInt):
        v = "number"
    elif isinstance(value, (t.String, t.URL)):
        v = "string"
    elif isinstance(value, t.Email):
        v = "email"
    elif isinstance(value, t.ToFloat):
        v = "float"
    elif isinstance(value, t.Enum):
        v = "choice"
    elif isinstance(value, (t.Dict, t.List)):
        v = "json"
    elif isinstance(value, (t.Bool, t.StrBool)):
        v = "boolean"
    elif isinstance(value, DateTime):
        v = "datetime"
    else:
        v = "string"
    return name, v, extra 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:24,代码来源:layout_utils.py

示例2: document_schema

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例3: test_dict

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例4: test_add_kwargs_ignore

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例5: test_add_kwargs_extra

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例6: test_base3

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例7: test_xor_key

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def test_xor_key(self):
        trafaret = t.Dict(xor_key('name', 'nick', t.String()))

        res = trafaret({'name': u'Nickolay'})
        assert res == {'name': u'Nickolay'}

        res = catch_error(trafaret, {'name': u'Nickolay', 'nick': u'Sveta'})
        assert res.as_dict() == {
            'name': 'correct only if nick is not defined',
            'nick': 'correct only if name is not defined',
        }
        res = catch_error(trafaret, {})
        assert res.as_dict() == {
            'name': 'is required if nick is not defined',
            'nick': 'is required if name is not defined',
        } 
开发者ID:Deepwalker,项目名称:trafaret,代码行数:18,代码来源:test_keys.py

示例8: mutate

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例9: get_info

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def get_info(request: web.Request, row: VFolderRow) -> web.Response:
    resp: Dict[str, Any] = {}
    folder_name = request.match_info['name']
    access_key = request['keypair']['access_key']
    log.info('VFOLDER.GETINFO (ak:{}, vf:{})', access_key, folder_name)
    if row['permission'] is None:
        is_owner = True
        permission = VFolderPermission.OWNER_PERM
    else:
        is_owner = row['is_owner']
        permission = row['permission']
    # TODO: handle nested directory structure
    folder_path = get_folder_hostpath(row, request.app)
    loop = current_loop()
    num_files = await loop.run_in_executor(None, lambda: len(list(folder_path.iterdir())))
    resp = {
        'name': row['name'],
        'id': row['id'].hex,
        'host': row['host'],
        'numFiles': num_files,  # legacy
        'num_files': num_files,
        'created': str(row['created_at']),  # legacy
        'created_at': str(row['created_at']),
        'last_used': str(row['created_at']),
        'user': str(row['user']),
        'group': str(row['group']),
        'type': 'user' if row['user'] is not None else 'group',
        'is_owner': is_owner,
        'permission': permission,
    }
    return web.json_response(resp, status=200) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:33,代码来源:vfolder.py

示例10: rename_file

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def rename_file(request: web.Request, params: Any, row: VFolderRow) -> web.Response:
    folder_name = request.match_info['name']
    access_key = request['keypair']['access_key']
    log.info('VFOLDER.RENAME_FILE (ak:{}, vf:{}, target_path:{}, new_name:{})',
             access_key, folder_name, params['target_path'], params['new_name'])
    folder_path = get_folder_hostpath(row, request.app)
    ops = []
    try:
        target_path = (folder_path / params['target_path']).resolve(strict=True)
        target_path.relative_to(folder_path)
        new_path = target_path.parent / params['new_name']
        # Ensure new file is in the same directory.
        if len(params['new_name'].split('/')) > 1:
            raise InvalidAPIParameters('New name should not be a path: ' + params['new_name'])
        if new_path.exists():
            raise InvalidAPIParameters('File already exists: ' + params['new_name'])
    except FileNotFoundError:
        raise InvalidAPIParameters('No such target file: ' + params['target_path'])
    except ValueError:
        raise InvalidAPIParameters('The requested path is out of the folder')
    ops.append(functools.partial(target_path.rename, new_path))

    def _do_ops():
        for op in ops:
            op()

    loop = current_loop()
    await loop.run_in_executor(None, _do_ops)
    resp: Dict[str, Any] = {}
    return web.json_response(resp, status=200) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:32,代码来源:vfolder.py

示例11: delete_files

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def delete_files(request: web.Request, params: Any, row: VFolderRow) -> web.Response:
    folder_name = request.match_info['name']
    access_key = request['keypair']['access_key']
    recursive = params['recursive']
    log.info('VFOLDER.DELETE_FILES (ak:{}, vf:{}, path:{}, recursive:{})',
             access_key, folder_name, folder_name, recursive)
    folder_path = get_folder_hostpath(row, request.app)
    ops = []
    for file in params['files']:
        try:
            file_path = (folder_path / file).resolve()
            file_path.relative_to(folder_path)
        except ValueError:
            # path is out of folder
            continue
        if file_path.is_dir():
            if recursive:
                ops.append(functools.partial(shutil.rmtree, file_path))
            else:
                raise InvalidAPIParameters(
                    f'"{file_path}" is a directory. '
                    'Set recursive option to remove it.')
        elif file_path.is_file():
            ops.append(functools.partial(os.unlink, file_path))

    def _do_ops():
        for op in ops:
            op()

    loop = current_loop()
    await loop.run_in_executor(None, _do_ops)
    resp: Dict[str, Any] = {}
    return web.json_response(resp, status=200) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:35,代码来源:vfolder.py

示例12: create_validator

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def create_validator(schema, primary_key):
    # create validator without primary key, used for update queries
    # where pk supplied in url and rest in body
    keys = [s for s in schema.keys if s.get_name() != primary_key]
    return t.Dict().merge(keys).ignore_extra(primary_key) 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:7,代码来源:mongo_utils.py

示例13: table_to_trafaret

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [as 别名]
def table_to_trafaret(table, primary_key, skip_pk=False):
    trafaret = {}
    for name, column in table.c.items():
        if skip_pk and column.name == primary_key:
            continue
        default = column.server_default
        key = build_key(name, default)

        traf_field = build_field(column)
        trafaret[key] = traf_field
    return t.Dict(trafaret).ignore_extra(primary_key) 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:13,代码来源:sa_utils.py

示例14: test_validate_payload

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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

示例15: test_validate_payload_not_valid_schema

# 需要导入模块: import trafaret [as 别名]
# 或者: from trafaret import Dict [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


注:本文中的trafaret.Dict方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。