本文整理匯總了Python中trafaret.Null方法的典型用法代碼示例。如果您正苦於以下問題:Python trafaret.Null方法的具體用法?Python trafaret.Null怎麽用?Python trafaret.Null使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類trafaret
的用法示例。
在下文中一共展示了trafaret.Null方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: build_field
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def build_field(column):
field = build_trafaret(column.type)
if column.nullable:
field |= t.Null
return field
示例2: test_async_or
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_async_or():
trafaret = t.ToInt | t.Null
res = await trafaret.async_check(None)
assert res is None
res = await trafaret.async_check('5')
assert res == 5
with pytest.raises(t.DataError) as res:
await trafaret.async_check('blablabla')
assert res.value.as_dict() == {
0: 'value can\'t be converted to int',
1: 'value should be None',
}
示例3: test_tuple
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_tuple():
trafaret = t.Tuple(t.Null, t.ToInt & check_int)
res = await (trafaret.async_check([None, '5']))
assert res == (None, 5)
with pytest.raises(t.DataError) as res:
await (trafaret.async_check((None, '5qwe')))
assert res.value.as_dict() == {1: "value can't be converted to int"}
示例4: test_null
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_null(self):
res = t.Null().check(None)
assert res is None
res = extract_error(t.Null(), 1)
assert res == 'value should be None'
示例5: test_repr
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_repr(self):
res = t.Null()
assert repr(res) == '<Null>'
示例6: test_or
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_or(self):
null_string = t.Or(t.String, t.Null)
res = null_string.check(None)
assert res is None
res = null_string.check(u"test")
assert res == u'test'
res = extract_error(null_string, 1)
assert res == {0: 'value is not a string', 1: 'value should be None'}
示例7: test_nullable_datetime
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_nullable_datetime(self):
nullable_datetime = t.Or(DateTime, t.Null)
assert nullable_datetime.check(None) is None
assert nullable_datetime.check(datetime.datetime(2017, 9, 1, 23, 59)) == datetime.datetime(2017, 9, 1, 23, 59)
assert nullable_datetime.check('2017-09-01 23:59') == datetime.datetime(2017, 9, 1, 23, 59)
示例8: test_nullable_date
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def test_nullable_date(self):
nullable_date = t.Or(Date, t.Null)
assert nullable_date.check(None) is None
assert nullable_date.check(datetime.date(1954, 7, 29)) == datetime.date(1954, 7, 29)
assert nullable_date.check('1954-07-29') == datetime.date(1954, 7, 29)
示例9: __init__
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [as 別名]
def __init__(self, allow_extra):
self.schema = t.Dict({
'id': t.Int(),
'client_name': t.String(max_length=255),
'sort_index': t.Float,
# t.Key('client_email', optional=True): t.Or(t.Null | t.Email()),
t.Key('client_phone', optional=True): t.Or(t.Null | t.String(max_length=255)),
t.Key('location', optional=True): t.Or(t.Null | t.Dict({
'latitude': t.Or(t.Float | t.Null),
'longitude': t.Or(t.Float | t.Null),
})),
t.Key('contractor', optional=True): t.Or(t.Null | t.Int(gt=0)),
t.Key('upstream_http_referrer', optional=True): t.Or(t.Null | t.String(max_length=1023)),
t.Key('grecaptcha_response'): t.String(min_length=20, max_length=1000),
t.Key('last_updated', optional=True): t.Or(t.Null | t.String >> parse),
t.Key('skills', default=[]): t.List(t.Dict({
'subject': t.String,
'subject_id': t.Int,
'category': t.String,
'qual_level': t.String,
'qual_level_id': t.Int,
t.Key('qual_level_ranking', default=0): t.Float,
})),
})
if allow_extra:
self.schema.allow_extra('*')
示例10: download_with_token
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import Null [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
])
})