本文整理匯總了Python中trafaret.Bool方法的典型用法代碼示例。如果您正苦於以下問題:Python trafaret.Bool方法的具體用法?Python trafaret.Bool怎麽用?Python trafaret.Bool使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類trafaret
的用法示例。
在下文中一共展示了trafaret.Bool方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: build_field
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [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: test_bool
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def test_bool(self, check_value, result):
res = t.Bool().check(check_value)
assert res == result
示例3: test_extract_error
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def test_extract_error(self):
err = extract_error(t.Bool(), 1)
assert err == 'value should be True or False'
示例4: test_repr
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def test_repr(self):
assert repr(t.Bool()) == '<Bool>'
示例5: test_on_error_ensured_trafaret
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def test_on_error_ensured_trafaret(self):
trafaret = t.OnError(t.Bool, message='Changed message')
res = trafaret(False)
assert res is False
示例6: test_on_error_data_error
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def test_on_error_data_error(self):
trafaret = t.OnError(t.Bool, message='Changed message')
res = catch_error(trafaret, 'Trololo')
assert res.as_dict() == 'Changed message'
示例7: construct
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def construct(arg):
'''
Shortcut syntax to define trafarets.
- int, str, float and bool will return t.Int, t.String, t.Float and t.Bool
- one element list will return t.List
- tuple or list with several args will return t.Tuple
- dict will return t.Dict. If key has '?' at the and it will be optional and '?' will be removed
- any callable will be t.Call
- otherwise it will be returned as is
construct is recursive and will try construct all lists, tuples and dicts args
'''
if isinstance(arg, t.Trafaret):
return arg
elif isinstance(arg, tuple) or (isinstance(arg, list) and len(arg) > 1):
return t.Tuple(*(construct(a) for a in arg))
elif isinstance(arg, list):
# if len(arg) == 1
return t.List(construct(arg[0]))
elif isinstance(arg, dict):
return t.Dict({construct_key(key): construct(value) for key, value in arg.items()})
elif isinstance(arg, str):
return t.Atom(arg)
elif isinstance(arg, type):
if arg is int:
return t.ToInt()
elif arg is float:
return t.ToFloat()
elif arg is str:
return t.String()
elif arg is bool:
return t.Bool()
else:
return t.Type(arg)
elif callable(arg):
return t.Call(arg)
else:
return arg
示例8: download_with_token
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Bool [as 別名]
def download_with_token(request) -> web.StreamResponse:
try:
secret = request.app['config']['manager']['secret']
token = request.query.get('token', '')
params = jwt.decode(token, secret, algorithms=['HS256'])
except jwt.PyJWTError:
log.exception('jwt error while parsing "{}"', token)
raise InvalidAPIParameters('Could not validate the download token.')
iv = t.Dict({
t.Key('file'): t.String,
t.Key('host'): t.String,
t.Key('id'): t.String,
t.Key('exp'): t.Int,
t.Key('archive', default=False): t.Bool | t.Null,
})
params = iv.check(params)
fn = params['file']
log.info('VFOLDER.DOWNLOAD_WITH_TOKEN (token:{}, path:{})', token, fn)
dbpool = request.app['dbpool']
async with dbpool.acquire() as conn:
query = (sa.select([vfolders.c.unmanaged_path])
.select_from(vfolders)
.where(vfolders.c.id == params['id'])
.limit(1))
unmanaged_path = await conn.scalar(query)
if unmanaged_path:
folder_path = Path(unmanaged_path)
else:
folder_path = (request.app['VFOLDER_MOUNT'] / params['host'] /
request.app['VFOLDER_FSPREFIX'] / params['id'])
try:
file_path = (folder_path / fn).resolve()
file_path.relative_to(folder_path)
if not file_path.exists():
raise FileNotFoundError
except (ValueError, FileNotFoundError):
raise InvalidAPIParameters('The file is not found.')
if not file_path.is_file():
if params['archive']:
# Download directory as an archive when archive param is set.
return await download_directory_as_archive(request, file_path)
else:
raise InvalidAPIParameters('The file is not a regular file.')
if request.method == 'HEAD':
return web.Response(status=200, headers={
hdrs.ACCEPT_RANGES: 'bytes',
hdrs.CONTENT_LENGTH: str(file_path.stat().st_size),
})
ascii_filename = file_path.name.encode('ascii', errors='ignore').decode('ascii').replace('"', r'\"')
encoded_filename = urllib.parse.quote(file_path.name, encoding='utf-8')
return web.FileResponse(file_path, headers={
hdrs.CONTENT_TYPE: "application/octet-stream",
hdrs.CONTENT_DISPOSITION: " ".join([
"attachment;"
f"filename=\"{ascii_filename}\";", # RFC-2616 sec2.2
f"filename*=UTF-8''{encoded_filename}", # RFC-5987
])
})