本文整理匯總了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
示例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
示例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'}
示例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'})
示例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})
示例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}
示例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',
}
示例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))
示例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)
示例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)
示例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)
示例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)
示例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)
示例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'}
示例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'