本文整理匯總了Python中trafaret.DataError方法的典型用法代碼示例。如果您正苦於以下問題:Python trafaret.DataError方法的具體用法?Python trafaret.DataError怎麽用?Python trafaret.DataError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類trafaret
的用法示例。
在下文中一共展示了trafaret.DataError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: perform_scheduler_ops
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def perform_scheduler_ops(request: web.Request, params: Any) -> web.Response:
try:
args = iv_scheduler_ops_args[params['op']].check(params['args'])
except t.DataError as e:
raise InvalidAPIParameters(
f"Input validation failed for args with {params['op']}",
extra_data=e.as_dict(),
)
if params['op'] in (SchedulerOps.INCLUDE_AGENTS, SchedulerOps.EXCLUDE_AGENTS):
schedulable = (params['op'] == SchedulerOps.INCLUDE_AGENTS)
async with request.app['dbpool'].acquire() as conn, conn.begin():
query = (
agents.update()
.values(schedulable=schedulable)
.where(agents.c.id.in_(args))
)
result = await conn.execute(query)
if result.rowcount < len(args):
raise InstanceNotFound()
if schedulable:
# trigger scheduler
await request.app['event_dispatcher'].produce_event('do_schedule')
else:
raise GenericBadRequest('Unknown scheduler operation')
return web.Response(status=204)
示例2: validate_query_structure
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def validate_query_structure(query):
"""Validate query arguments in list request.
:param query: mapping with pagination and filtering information
"""
query_dict = dict(query)
filters = query_dict.pop('_filters', None)
if filters:
try:
f = json.loads(filters)
except ValueError:
msg = '_filters field can not be serialized'
raise JsonValidaitonError(msg)
else:
query_dict['_filters'] = f
try:
q = ListQuery(query_dict)
except t.DataError as exc:
msg = '_filters query invalid'
raise JsonValidaitonError(msg, **as_dict(exc))
return q
示例3: test_dict
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [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_mapping
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def test_mapping():
trafaret = t.Mapping(t.String, t.ToInt & check_int)
res = await (trafaret.async_check({'a': '5'}))
assert res == {'a': 5}
# bad key
with pytest.raises(t.DataError) as res:
await (trafaret.async_check({None: '5'}))
assert res.value.as_dict() == {None: {"key": "value is not a string"}}
# bad value
with pytest.raises(t.DataError) as res:
await (trafaret.async_check({'b': 'qwe'}))
assert res.value.as_dict() == {'b': {"value": "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"
示例5: test_add_kwargs_extra
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [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_nested_dataerror_value
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def test_nested_dataerror_value():
error = t.DataError(
error={0: t.DataError(error='Wait for good value', value='BAD ONE', code='bad_value')},
code='some_elements_going_mad',
)
assert error.as_dict() == {0: 'Wait for good value'}
assert error.as_dict(value=True) == {0: "Wait for good value, got 'BAD ONE'"}
assert error.to_struct() == {
'code': 'some_elements_going_mad',
'nested': {0: {
'code': 'bad_value',
'message': 'Wait for good value',
}},
}
assert error.to_struct(value=True) == {
'code': 'some_elements_going_mad',
'nested': {0: {
'code': 'bad_value',
'message': "Wait for good value, got 'BAD ONE'",
}},
}
示例7: evaluate
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def evaluate(request: Request):
app: Application = request.app
student_id = int(request.match_info['student_id'])
course_id = int(request.match_info['course_id'])
data = await request.post()
async with app['db'].acquire() as conn:
student = await Student.get(conn, student_id)
course = await Course.get(conn, course_id)
if not student or not course:
raise HTTPNotFound()
try:
data = EVALUATE_SCHEMA.check_and_return(data)
except DataError as e:
return {'errors': e.as_dict(),
'course': course,
'student': student}
await Mark.create(conn, student_id, course_id,
data['points'])
raise HTTPFound(f'/courses/{course_id}')
示例8: check_api_params
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def check_api_params(checker: t.Trafaret, loads: Callable[[str], Any] = None,
query_param_checker: t.Trafaret = None) -> Any:
# FIXME: replace ... with [web.Request, Any...] in the future mypy
def wrap(handler: Callable[..., Awaitable[web.Response]]):
@functools.wraps(handler)
async def wrapped(request: web.Request, *args, **kwargs) -> web.Response:
orig_params: Any
body: str = ''
try:
body_exists = request.can_read_body
if body_exists:
body = await request.text()
if request.content_type == 'text/yaml':
orig_params = yaml.load(body, Loader=yaml.BaseLoader)
else:
orig_params = (loads or json.loads)(body)
else:
orig_params = dict(request.query)
stripped_params = orig_params.copy()
stripped_params.pop('owner_access_key', None)
log.debug('stripped raw params: {}', mask_sensitive_keys(stripped_params))
checked_params = checker.check(stripped_params)
if body_exists and query_param_checker:
query_params = query_param_checker.check(request.query)
kwargs['query'] = query_params
except (json.decoder.JSONDecodeError, yaml.YAMLError, yaml.MarkedYAMLError):
raise InvalidAPIParameters('Malformed body')
except t.DataError as e:
raise InvalidAPIParameters('Input validation error',
extra_data=e.as_dict())
return await handler(request, checked_params, *args, **kwargs)
return wrapped
return wrap
示例9: validate_payload
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def validate_payload(raw_payload, schema):
payload = raw_payload.decode(encoding='UTF-8')
try:
parsed = json.loads(payload)
except ValueError:
raise JsonValidaitonError('Payload is not json serialisable')
try:
data = schema(parsed)
except t.DataError as exc:
raise JsonValidaitonError(**as_dict(exc))
return data
示例10: apply_trafaret
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def apply_trafaret(trafaret, value):
validate = trafaret.check_and_return
if isinstance(trafaret, MongoId):
validate = trafaret.check_and_return
if isinstance(value, list):
try:
value = validate(value)
except t.DataError:
value = [validate(v) for v in value]
else:
value = validate(value)
return value
示例11: _check_value
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def _check_value(column_traf_map, field_name, value):
# at this point we sure that field name is present in schema
# validation should be done earlier
trafaret = column_traf_map[field_name]
try:
value = apply_trafaret(trafaret, value)
except t.DataError as exc:
raise JsonValidaitonError(**as_dict(exc))
return value
示例12: check_value
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def check_value(column, value):
trafaret = build_trafaret(column.type)
try:
if isinstance(value, list):
value = [trafaret.check_and_return(v) for v in value]
else:
value = trafaret.check_and_return(value)
except t.DataError as exc:
raise JsonValidaitonError(**as_dict(exc))
return value
示例13: test_as_dict
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def test_as_dict():
exc = t.DataError('err')
resp = as_dict(exc)
assert isinstance(resp, dict)
exc = t.DataError('err')
assert isinstance(exc.as_dict("boom"), str)
resp = as_dict(exc, 'boom')
assert isinstance(resp, dict)
示例14: verify_objectid
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def verify_objectid(value):
"""Verify if id_ is a proper ObjectId. """
try:
t.Regexp(regexp='^[A-Fa-f0-9]{24}$').check(value)
except t.DataError:
raise ValueError('id {} not a valid project/model id'.format(value))
示例15: check_int_context
# 需要導入模塊: import trafaret [as 別名]
# 或者: from trafaret import DataError [as 別名]
def check_int_context(value, context=None):
if context is not None and value > context:
return t.DataError('too big', code='too_big')
return value