本文整理汇总了Python中middlewared.service.ValidationErrors.check方法的典型用法代码示例。如果您正苦于以下问题:Python ValidationErrors.check方法的具体用法?Python ValidationErrors.check怎么用?Python ValidationErrors.check使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类middlewared.service.ValidationErrors
的用法示例。
在下文中一共展示了ValidationErrors.check方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_create
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def do_create(self, data):
"""
Create AFP share.
`allow`, `deny`, `ro`, and `rw` are lists of users and groups. Groups are designated by
an @ prefix.
`hostsallow` and `hostsdeny` are lists of hosts and/or networks.
"""
verrors = ValidationErrors()
path = data['path']
await self.clean(data, 'sharingafp_create', verrors)
await self.validate(data, 'sharingafp_create', verrors)
await check_path_resides_within_volume(
verrors, self.middleware, 'sharingafp_create.path', path)
verrors.check()
if path and not os.path.exists(path):
try:
os.makedirs(path)
except OSError as e:
raise CallError(f'Failed to create {path}: {e}')
await self.compress(data)
data['id'] = await self.middleware.call(
'datastore.insert', self._config.datastore, data,
{'prefix': self._config.datastore_prefix})
await self.extend(data)
await self._service_change('afp', 'reload')
return data
示例2: do_update
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def do_update(self, data):
"""
Update AFP service settings.
`bindip` is a list of IPs to bind AFP to. Leave blank (empty list) to bind to all
available IPs.
`map_acls` defines how to map the effective permissions of authenticated users.
RIGHTS - Unix-style permissions
MODE - ACLs
NONE - Do not map
`chmod_request` defines advanced permission control that deals with ACLs.
PRESERVE - Preserve ZFS ACEs for named users and groups or POSIX ACL group mask
SIMPLE - Change permission as requested without any extra steps
IGNORE - Permission change requests are ignored
"""
old = await self.config()
new = old.copy()
new.update(data)
verrors = ValidationErrors()
if new['dbpath']:
await check_path_resides_within_volume(
verrors, self.middleware, 'afp_update.dbpath', new['dbpath'],
)
verrors.check()
new = await self.compress(new)
await self._update_service(old, new)
return await self.config()
示例3: do_create
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def do_create(self, data):
"""
Create a new group.
If `gid` is not provided it is automatically filled with the next one available.
`allow_duplicate_gid` allows distinct group names to share the same gid.
`users` is a list of user ids (`id` attribute from `user.query`).
"""
verrors = ValidationErrors()
await self.__common_validation(verrors, data, 'group_create')
verrors.check()
if not data.get('gid'):
data['gid'] = await self.get_next_gid()
group = data.copy()
group['group'] = group.pop('name')
users = group.pop('users', [])
pk = await self.middleware.call('datastore.insert', 'account.bsdgroups', group, {'prefix': 'bsdgrp_'})
for user in users:
await self.middleware.call('datastore.insert', 'account.bsdgroupmembership', {'bsdgrpmember_group': pk, 'bsdgrpmember_user': user})
await self.middleware.call('service.reload', 'user')
await self.middleware.call('smb.groupmap_add', data['name'])
return pk
示例4: __rquery_to_start_end
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
def __rquery_to_start_end(self, query):
unit = query.get('unit')
if unit:
verrors = ValidationErrors()
for i in ('start', 'end'):
if i in query:
verrors.add(
f'reporting_query.{i}',
f'{i!r} should only be used if "unit" attribute is not provided.',
)
verrors.check()
else:
if 'start' not in query:
unit = 'HOURLY'
else:
starttime = query['start']
endtime = query.get('end') or 'now'
if unit:
unit = unit[0].lower()
page = query['page']
starttime = f'end-{page + 1}{unit}'
if not page:
endtime = 'now'
else:
endtime = f'now-{page}{unit}'
return starttime, endtime
示例5: do_update
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def do_update(self, pk, data):
"""
Update attributes of an existing group.
"""
group = await self._get_instance(pk)
verrors = ValidationErrors()
await self.__common_validation(verrors, data, 'group_update', pk=pk)
verrors.check()
group.update(data)
delete_groupmap = False
group.pop('users', None)
if 'name' in data and data['name'] != group['group']:
delete_groupmap = group['group']
group['group'] = group.pop('name')
else:
group.pop('name', None)
await self.middleware.call('datastore.update', 'account.bsdgroups', pk, group, {'prefix': 'bsdgrp_'})
if 'users' in data:
existing = {i['bsdgrpmember_user']['id']: i for i in await self.middleware.call('datastore.query', 'account.bsdgroupmembership', [('bsdgrpmember_group', '=', pk)])}
to_remove = set(existing.keys()) - set(data['users'])
for i in to_remove:
await self.middleware.call('datastore.delete', 'account.bsdgroupmembership', existing[i]['id'])
to_add = set(data['users']) - set(existing.keys())
for i in to_add:
await self.middleware.call('datastore.insert', 'account.bsdgroupmembership', {'bsdgrpmember_group': pk, 'bsdgrpmember_user': i})
if delete_groupmap:
await self.middleware.call('notifier.groupmap_delete', delete_groupmap)
await self.middleware.call('service.reload', 'user')
await self.middleware.call('smb.groupmap_add', group['group'])
return pk
示例6: validate_data_keys
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
def validate_data_keys(self, data, model, schema, prefix):
verrors = ValidationErrors()
fields = list(
map(
lambda f: f.name.replace(prefix or '', '', 1),
chain(model._meta.fields, model._meta.many_to_many)
)
)
# _id is a special condition in filter where the key in question can be a related descriptor in django
# i.e share_id - so we remove _id and check if the field is present in `fields` list
for key in filter(
lambda v: all(c not in fields for c in (v, v if not v.endswith('_id') else v[:-3])),
data
):
verrors.add(
f'{schema}.{key}',
f'{key} field not recognized'
)
verrors.check()
示例7: common_validation
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def common_validation(self, data, schema_name):
verrors = ValidationErrors()
await check_path_resides_within_volume(verrors, self.middleware, f'{schema_name}.path', data.get('path'))
for entity in ('user', 'group'):
value = data.get(entity)
if value not in map(
lambda e: e[entity if entity == 'group' else 'username'],
await self.middleware.call(f'{entity}.query')
):
verrors.add(
f'{schema_name}.{entity}',
f'Please specify a valid {entity}'
)
verrors.check()
data['hostsallow'] = ' '.join(data['hostsallow'])
data['hostsdeny'] = ' '.join(data['hostsdeny'])
data['mode'] = data['mode'].lower()
return data
示例8: do_update
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
async def do_update(self, job, data):
"""
Update System Dataset Service Configuration.
`pool` is the name of a valid pool configured in the system which will be used to host the system dataset.
`pool_exclude` can be specified to make sure that we don't place the system dataset on that pool if `pool`
is not provided.
"""
config = await self.config()
new = config.copy()
new.update(data)
verrors = ValidationErrors()
if new['pool'] and new['pool'] != 'freenas-boot':
pool = await self.middleware.call('pool.query', [['name', '=', new['pool']]])
if not pool:
verrors.add(
'sysdataset_update.pool',
f'Pool "{new["pool"]}" not found',
errno.ENOENT
)
elif pool[0]['encrypt'] == 2:
# This will cover two cases - passphrase being set for a pool and that it might be locked as well
verrors.add(
'sysdataset_update.pool',
f'Pool "{new["pool"]}" has an encryption passphrase set. '
'The system dataset cannot be placed on this pool.'
)
elif not new['pool']:
for pool in await self.middleware.call(
'pool.query', [
['encrypt', '!=', 2]
]
):
if data.get('pool_exclude') == pool['name']:
continue
new['pool'] = pool['name']
break
else:
# If a data pool could not be found, reset it to blank
# Which will eventually mean its back to freenas-boot (temporarily)
new['pool'] = ''
verrors.check()
new['syslog_usedataset'] = new['syslog']
update_dict = new.copy()
for key in ('is_decrypted', 'basename', 'uuid_a', 'syslog', 'path', 'pool_exclude'):
update_dict.pop(key, None)
await self.middleware.call(
'datastore.update',
'system.systemdataset',
config['id'],
update_dict,
{'prefix': 'sys_'}
)
new = await self.config()
if config['pool'] != new['pool']:
await self.migrate(config['pool'], new['pool'])
await self.setup(True, data.get('pool_exclude'))
if config['syslog'] != new['syslog']:
await self.middleware.call('service.restart', 'syslogd')
return await self.config()
示例9: validate_attrs
# 需要导入模块: from middlewared.service import ValidationErrors [as 别名]
# 或者: from middlewared.service.ValidationErrors import check [as 别名]
#.........这里部分代码省略.........
continue
if i.startswith('[') and not i.endswith(']'):
verrors.add(
'netdata_update.additional_params',
f'Please correct format for {i}. i.e [system.intr]'
)
elif not i.startswith('[') and '=' not in i:
verrors.add(
'netdata_update.additional_params',
f'Please correct format for {i}. i.e enabled = yes'
)
if i.startswith('['):
param_str += f'\n\n{i}'
else:
param_str += f'\n\t{i}'
data['additional_params'] = param_str + '\n'
bind_to_ips = data.get('bind')
if bind_to_ips:
valid_ips = [ip['address'] for ip in await self.middleware.call('interface.ip_in_use')]
valid_ips.extend(['127.0.0.1', '::1', '0.0.0.0', '::'])
for bind_ip in bind_to_ips:
if bind_ip not in valid_ips:
verrors.add(
'netdata_update.bind',
f'Invalid {bind_ip} bind IP'
)
else:
verrors.add(
'netdata_update.bind',
'This field is required'
)
update_alarms = data.pop('update_alarms', {})
valid_alarms = self._alarms
if update_alarms:
for alarm in update_alarms:
if alarm not in valid_alarms:
verrors.add(
'netdata_update.alarms',
f'{alarm} not a valid alarm'
)
verrors.extend(
validate_attributes(
[Dict(key, Bool('enabled', required=True)) for key in update_alarms],
{'attributes': update_alarms}
)
)
# Validating streaming metrics now
stream_mode = data.get('stream_mode')
if stream_mode == 'SLAVE':
for key in ('api_key', 'destination'):
if not data.get(key):
verrors.add(
f'netdata_update.{key}',
f'{key} is required with stream mode as SLAVE'
)
destinations = data.get('destination')
if destinations:
ip_addr = IpAddress()
port = Port()
for dest in destinations:
ip = dest.split(':')[0]
try:
ip_addr(ip)
except ValueError as e:
verrors.add(
'netdata_update.destination',
str(e)
)
else:
if ':' in dest:
try:
port(int(dest.split(':')[1]))
except ValueError as e:
verrors.add(
'netdata_update.destination',
f'Not a valid port: {e}'
)
elif stream_mode == 'MASTER':
for key in ('allow_from', 'api_key'):
if not data.get(key):
verrors.add(
f'netdata_update.{key}',
f'{key} is required with stream mode as MASTER'
)
verrors.check()
data['alarms'].update(update_alarms)
return data