本文整理汇总了Python中cerberus.Validator类的典型用法代码示例。如果您正苦于以下问题:Python Validator类的具体用法?Python Validator怎么用?Python Validator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Validator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
def post(self):
us = ServiceLocator.resolve(ServiceLocator.USERS)
v = Validator(check_params_schema)
args = v.validated(request.get_json())
if args is None:
return ApiResponse(status=4001, errors=v.errors)
try:
login = args.get('login', None)
email = args.get('email', None)
login_result = login and us.check_login(login)
email_result = email and us.check_email(email)
return {
'login': login_result,
'email': email_result
}
except Exception as ex:
error(u'UsersCheckAPI.post', ex)
return {
'login': None,
'email': None
}
示例2: validate
def validate(self):
"""
Validates the action_block based on the cerberus schema
example:
action_block :: sample ::
- name: manipulate_inventory
type: shell
path: /tmp/shellscripts
actions:
- thisisshell.sh
"""
schema = {
'name': {'type': 'string', 'required': True},
'type': {
'type': 'string',
'allowed': ['shell', 'subprocess']
},
'path': {'type': 'string', 'required': False},
'context': {'type': 'boolean', 'required': False},
'actions': {
'type': 'list',
'schema': {'type': 'string'},
'required': True
}
}
v = Validator(schema)
status = v.validate(self.action_data)
if not status:
raise HookError("Invalid Syntax: {0}".format(str(v.errors)))
else:
return status
示例3: _validate
def _validate(self, doc, **kwargs):
lookup = {'act': doc['act'], 'type': doc[ITEM_TYPE]}
use_headline = kwargs and 'headline' in kwargs
validators = superdesk.get_resource_service('validators').get(req=None, lookup=lookup)
for validator in validators:
v = Validator()
v.allow_unknown = True
v.validate(doc['validate'], validator['schema'])
error_list = v.errors
response = []
for e in error_list:
if error_list[e] == 'required field' or type(error_list[e]) is dict:
message = '{} is a required field'.format(e.upper())
elif 'min length is' in error_list[e]:
message = '{} is too short'.format(e.upper())
elif 'max length is' in error_list[e]:
message = '{} is too long'.format(e.upper())
else:
message = '{} {}'.format(e.upper(), error_list[e])
if use_headline:
response.append('{}: {}'.format(doc['validate'].get('headline',
doc['validate'].get('_id')), message))
else:
response.append(message)
return response
else:
return ['validator was not found for {}'.format(doc['act'])]
示例4: registration
async def registration(request: web.Request) -> Dict:
payload = await base.get_payload(request)
validator = Validator(schema=users.schema)
if not validator.validate(payload):
raise ValidationError(validator.errors)
async with request.app['engine'].acquire() as conn:
count = await conn.scalar(
sqlalchemy.select([sqlalchemy.func.count()])
.select_from(users.table)
.where(users.table.c.login == payload['login'])
)
if count:
raise ValidationError({'login': 'Already exists'})
user = {
'login': payload['login'],
'password': users.encrypt_password(payload['password']),
'created_on': datetime.now()
}
user = await create_instance(user, users.table, conn)
return base.json_response({
'id': user['id'],
'login': user['login']
}, status=201)
示例5: __init__
def __init__(self, environment_name, nova_descriptor_file=None):
self._nova_descriptor_file = nova_descriptor_file or 'nova.yml'
self._environment_name = environment_name
self._environment = None
self._codedeploy_app = None
self.templates_used = dict()
yaml.add_constructor("!include", yaml_include)
with open(os.path.join(spec.__path__[0], 'nova_service_schema.yml'), 'r') as schemaYaml:
schema = yaml.load(schemaYaml)
v = Validator(schema)
try:
with open(self._nova_descriptor_file, 'r') as novaYaml:
self.service_spec = yaml.safe_load(novaYaml)
# Validate loaded dictionary
valid = v.validate(self.service_spec)
if not valid:
raise NovaError("Invalid nova service descriptor file '%s': %s" % (self._nova_descriptor_file, v.errors))
else:
self.service = Service.load(self.service_spec)
self.service_name = self.service.name
self.service_port = self.service.port
self.service_healthcheck_url = self.service.healthcheck_url
except IOError:
raise NovaError("No nova service descriptor found at '%s'" % self._nova_descriptor_file)
示例6: test_ignore_none_values
def test_ignore_none_values():
field = 'test'
schema = {field: {'type': 'string', 'empty': False, 'required': False}}
document = {field: None}
# Test normal behaviour
validator = Validator(schema, ignore_none_values=False)
assert_fail(document, validator=validator)
validator.schema[field]['required'] = True
validator.schema.validate()
_errors = assert_fail(document, validator=validator)
assert_not_has_error(_errors, field, (field, 'required'),
errors.REQUIRED_FIELD, True)
# Test ignore None behaviour
validator = Validator(schema, ignore_none_values=True)
validator.schema[field]['required'] = False
validator.schema.validate()
assert_success(document, validator=validator)
validator.schema[field]['required'] = True
_errors = assert_fail(schema=schema, document=document, validator=validator)
assert_has_error(_errors, field, (field, 'required'), errors.REQUIRED_FIELD,
True)
assert_not_has_error(_errors, field, (field, 'type'), errors.BAD_TYPE,
'string')
示例7: validate_filter
def validate_filter(filter):
for key, value in filter.items():
if '*' not in allowed and key not in allowed:
return "filter on '%s' not allowed" % key
if key in ('$or', '$and', '$nor'):
if not isinstance(value, list):
return "operator '%s' expects a list of sub-queries" % key
for v in value:
if not isinstance(v, dict):
return "operator '%s' expects a list of sub-queries" \
% key
r = validate_filter(v)
if r:
return r
else:
if config.VALIDATE_FILTERS:
res_schema = config.DOMAIN[resource]['schema']
if key not in res_schema:
return "filter on '%s' is invalid"
else:
field_schema = res_schema.get(key)
v = Validator({key: field_schema})
if not v.validate({key: value}):
return "filter on '%s' is invalid"
else:
return None
示例8: _validate_equals
def _validate_equals(self, ref_value, field, value):
""" {'type': 'string'} """
if isinstance(ref_value, list):
Validator._validate_allowed(self, ref_value, field, value)
else:
if value != ref_value:
self._error(field, "Must be equal to " + ref_value)
示例9: validate_info
def validate_info():
v = Validator()
schema = {
'title': {'required': True, 'type': 'string'},
'version': {'required': True, 'type': 'string'},
'description': {'type': 'string'},
'termsOfService': {'type': 'string'},
'contact': {
'type': 'dict',
'schema': {
'name': {'type': 'string'},
'url': {'type': 'string', 'validator': _validate_url},
'email': {
'type': 'string',
'regex':
'^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
}
}
},
'license': {
'type': 'dict',
'schema': {
'name': {'type': 'string', 'required': True},
'url': {'type': 'string', 'validator': _validate_url}
}
},
}
if eve_swagger.INFO not in app.config:
raise ConfigException('%s setting is required in Eve configuration.' %
eve_swagger.INFO)
if not v.validate(app.config[eve_swagger.INFO], schema):
raise ConfigException('%s is misconfigured: %s' % (
eve_swagger.INFO, v.errors))
示例10: confirm_friend
def confirm_friend():
user = current_user._get_current_object()
form = request.get_json()
schema = {
'id':{'type':'integer','empty':False}
}
v = Validator(schema)
if v.validate(form) is False:
return api_validation_error(v.errors)
friend_request = FriendRequests.query.filter(FriendRequests.id == form['id']).first()
if friend_request:
#we are confirming this, so create friendships that last both ways.
my_friend = Friends(user_id = user.id,friend_id = friend_request.friend_id)
their_friend = Friends(user_id = friend_request.friend_id,friend_id = user.id)
meeple.db.session.add(my_friend)
meeple.db.session.add(their_friend)
meeple.db.session.delete(friend_request) #remove this friend request
meeple.db.session.commit()
#now return who this friend is back to them.
return api_package(data=my_friend.as_dict())
else:
return api_error("This request does not exist")
示例11: add_friend_to_group
def add_friend_to_group(id):
user = current_user._get_current_object()
form = request.get_json()
schema = {
'id':{'type':'integer','empty':False},
}
v = Validator(schema)
if v.validate(form) is False:
return api_validation_error(v.errors)
#first see if this is a valid group
group = FriendsGroup.query.filter(and_(FriendsGroup.user_id == user.id,FriendsGroup.id == id)).first()
if group:
#lets see if this is a confirmed friend of yours
friend = Friends.query.filter(and_(Friends.user_id == user.id,Friends.friend_id == form['id'])).first()
if friend:
#lets see if this friend is not in this group
if friend.group_id == group.id:
return api_error("This friend is already in this group")
else:
friend.group_id = group.id
meeple.db.session.commit()
return api_package()
else:
return api_error("Friend does not exist")
else:
return api_error("This group does not exist.")
示例12: allowed_for_single_value
def allowed_for_single_value():
"""对于值进行限制, 只能使预定义的几个值中的一个。
"""
schema = {"label": {"type": "integer", "allowed": [1, 2, 3]}}
v = Validator(schema)
print(v.validate({"label": 1}))
示例13: check_bx_users
def check_bx_users(fn):
"""Check the consistentcy of the BX-Users.csv file.
"""
tab = etl.fromcsv(fn, delimiter=DELIMITER,
quoting=QUOTE_ALL, encoding=ENCODING)
v = Validator({
"User-ID" : {
"type" : "string",
"regex" : USER_ID_PAT,
"required" : True
},
"Location" : {
"type" : "string",
"required" : True
},
"Age" : {
"type" : "string",
"validator" : validate_age,
"required" : True
}
})
for row_num, r in enumerate(tab.dicts(), 1):
is_valid = v.validate(r)
if not is_valid:
print "row %d -> %r, %r" % (row_num, v.errors, r)
return
示例14: _validate_page
def _validate_page(self, page):
schema = {'page': {'type': 'integer', 'min': 1}}
v = Validator(schema)
try:
return v.validate({'page': int(page)})
except Exception:
return False
示例15: check_bx_book_ratings
def check_bx_book_ratings(fn):
"""Check the consistency of the BX-Book-Ratings.csv file.
"""
tab = etl.fromcsv(fn, delimiter=DELIMITER,
quoting=QUOTE_ALL, encoding=ENCODING)
v = Validator({
"User-ID" : {
"type" : "string",
"required" : True
},
"ISBN" : {
"type" : "string",
"required" : True
},
"Book-Rating" : {
"type" : "string",
"validator" : validate_rating,
"required" : True
}
})
for row_num, r in enumerate(tab.dicts(), 1):
is_valid = v.validate(r)
if not is_valid:
print "row %d -> %r, %r" % (row_num, v.errors, r)
return