本文整理汇总了Python中voluptuous.humanize.humanize_error函数的典型用法代码示例。如果您正苦于以下问题:Python humanize_error函数的具体用法?Python humanize_error怎么用?Python humanize_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了humanize_error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: post
async def post(self, request):
"""Accept the POST request for push registrations from a browser."""
try:
data = await request.json()
except ValueError:
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)
try:
data = REGISTER_SCHEMA(data)
except vol.Invalid as ex:
return self.json_message(
humanize_error(data, ex), HTTP_BAD_REQUEST)
name = self.find_registration_name(data)
previous_registration = self.registrations.get(name)
self.registrations[name] = data
try:
hass = request.app['hass']
await hass.async_add_job(save_json, self.json_path,
self.registrations)
return self.json_message(
'Push notification subscriber registered.')
except HomeAssistantError:
if previous_registration is not None:
self.registrations[name] = previous_registration
else:
self.registrations.pop(name)
return self.json_message(
'Error saving registration.', HTTP_INTERNAL_SERVER_ERROR)
开发者ID:EarthlingRich,项目名称:home-assistant,代码行数:33,代码来源:html5.py
示例2: async_log_exception
def async_log_exception(ex, domain, config, hass):
"""Generate log exception for configuration validation.
This method must be run in the event loop.
"""
message = "Invalid config for [{}]: ".format(domain)
if hass is not None:
async_notify_setup_error(hass, domain, True)
if 'extra keys not allowed' in ex.error_message:
message += '[{}] is an invalid option for [{}]. Check: {}->{}.'\
.format(ex.path[-1], domain, domain,
'->'.join(str(m) for m in ex.path))
else:
message += '{}.'.format(humanize_error(config, ex))
domain_config = config.get(domain, config)
message += " (See {}, line {}). ".format(
getattr(domain_config, '__config_file__', '?'),
getattr(domain_config, '__line__', '?'))
if domain != 'homeassistant':
message += ('Please check the docs at '
'https://home-assistant.io/components/{}/'.format(domain))
_LOGGER.error(message)
开发者ID:BaptisteSim,项目名称:home-assistant,代码行数:26,代码来源:config.py
示例3: _format_config_error
def _format_config_error(ex: vol.Invalid, domain: str, config: Dict) -> str:
"""Generate log exception for configuration validation.
This method must be run in the event loop.
"""
message = "Invalid config for [{}]: ".format(domain)
if 'extra keys not allowed' in ex.error_message:
message += '[{option}] is an invalid option for [{domain}]. ' \
'Check: {domain}->{path}.'.format(
option=ex.path[-1], domain=domain,
path='->'.join(str(m) for m in ex.path))
else:
message += '{}.'.format(humanize_error(config, ex))
try:
domain_config = config.get(domain, config)
except AttributeError:
domain_config = config
message += " (See {}, line {}). ".format(
getattr(domain_config, '__config_file__', '?'),
getattr(domain_config, '__line__', '?'))
if domain != CONF_CORE:
message += ('Please check the docs at '
'https://home-assistant.io/components/{}/'.format(domain))
return message
开发者ID:arsaboo,项目名称:home-assistant,代码行数:28,代码来源:config.py
示例4: log_exception
def log_exception(ex, domain, config, hass=None):
"""Generate log exception for config validation."""
message = "Invalid config for [{}]: ".format(domain)
if hass is not None:
_PERSISTENT_VALIDATION.add(domain)
message = (
"The following platforms contain invalid configuration: "
+ ", ".join(list(_PERSISTENT_VALIDATION))
+ " (please check your configuration)"
)
persistent_notification.create(hass, message, "Invalid config", "invalid_config")
if "extra keys not allowed" in ex.error_message:
message += "[{}] is an invalid option for [{}]. Check: {}->{}.".format(
ex.path[-1], domain, domain, "->".join("%s" % m for m in ex.path)
)
else:
message += "{}.".format(humanize_error(config, ex))
if hasattr(config, "__line__"):
message += " (See {}:{})".format(config.__config_file__, config.__line__ or "?")
if domain != "homeassistant":
message += " Please check the docs at " "https://home-assistant.io/components/{}/".format(domain)
_LOGGER.error(message)
开发者ID:krzynio,项目名称:home-assistant,代码行数:26,代码来源:bootstrap.py
示例5: async_handle
async def async_handle(self, msg):
"""Handle authentication."""
try:
msg = AUTH_MESSAGE_SCHEMA(msg)
except vol.Invalid as err:
error_msg = 'Auth message incorrectly formatted: {}'.format(
humanize_error(msg, err))
self._logger.warning(error_msg)
self._send_message(auth_invalid_message(error_msg))
raise Disconnect
if self._hass.auth.active and 'access_token' in msg:
self._logger.debug("Received access_token")
refresh_token = \
await self._hass.auth.async_validate_access_token(
msg['access_token'])
if refresh_token is not None:
return await self._async_finish_auth(
refresh_token.user, refresh_token)
elif ((not self._hass.auth.active or self._hass.auth.support_legacy)
and 'api_password' in msg):
self._logger.debug("Received api_password")
if validate_password(self._request, msg['api_password']):
return await self._async_finish_auth(None, None)
self._send_message(auth_invalid_message(
'Invalid access token or password'))
await process_wrong_login(self._request)
raise Disconnect
开发者ID:ManHammer,项目名称:home-assistant,代码行数:30,代码来源:auth.py
示例6: post
def post(self, request):
"""Accept the POST request for push registrations event callback."""
auth_check = self.check_authorization_header(request)
if not isinstance(auth_check, dict):
return auth_check
try:
data = yield from request.json()
except ValueError:
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)
event_payload = {
ATTR_TAG: data.get(ATTR_TAG),
ATTR_TYPE: data[ATTR_TYPE],
ATTR_TARGET: auth_check[ATTR_TARGET],
}
if data.get(ATTR_ACTION) is not None:
event_payload[ATTR_ACTION] = data.get(ATTR_ACTION)
if data.get(ATTR_DATA) is not None:
event_payload[ATTR_DATA] = data.get(ATTR_DATA)
try:
event_payload = CALLBACK_EVENT_PAYLOAD_SCHEMA(event_payload)
except vol.Invalid as ex:
_LOGGER.warning('Callback event payload is not valid! %s',
humanize_error(event_payload, ex))
event_name = '{}.{}'.format(NOTIFY_CALLBACK_EVENT,
event_payload[ATTR_TYPE])
self.hass.bus.fire(event_name, event_payload)
return self.json({'status': 'ok',
'event': event_payload[ATTR_TYPE]})
开发者ID:GadgetReactor,项目名称:home-assistant,代码行数:34,代码来源:html5.py
示例7: _event_to_service_call
async def _event_to_service_call(self, event: Event) -> None:
"""Handle the SERVICE_CALLED events from the EventBus."""
service_data = event.data.get(ATTR_SERVICE_DATA) or {}
domain = event.data.get(ATTR_DOMAIN).lower() # type: ignore
service = event.data.get(ATTR_SERVICE).lower() # type: ignore
call_id = event.data.get(ATTR_SERVICE_CALL_ID)
if not self.has_service(domain, service):
if event.origin == EventOrigin.local:
_LOGGER.warning("Unable to find service %s/%s",
domain, service)
return
service_handler = self._services[domain][service]
def fire_service_executed() -> None:
"""Fire service executed event."""
if not call_id:
return
data = {ATTR_SERVICE_CALL_ID: call_id}
if (service_handler.is_coroutinefunction or
service_handler.is_callback):
self._hass.bus.async_fire(EVENT_SERVICE_EXECUTED, data,
EventOrigin.local, event.context)
else:
self._hass.bus.fire(EVENT_SERVICE_EXECUTED, data,
EventOrigin.local, event.context)
try:
if service_handler.schema:
service_data = service_handler.schema(service_data)
except vol.Invalid as ex:
_LOGGER.error("Invalid service data for %s.%s: %s",
domain, service, humanize_error(service_data, ex))
fire_service_executed()
return
service_call = ServiceCall(
domain, service, service_data, event.context)
try:
if service_handler.is_callback:
service_handler.func(service_call)
fire_service_executed()
elif service_handler.is_coroutinefunction:
await service_handler.func(service_call)
fire_service_executed()
else:
def execute_service() -> None:
"""Execute a service and fires a SERVICE_EXECUTED event."""
service_handler.func(service_call)
fire_service_executed()
await self._hass.async_add_executor_job(execute_service)
except Exception: # pylint: disable=broad-except
_LOGGER.exception('Error executing service %s', service_call)
开发者ID:ManHammer,项目名称:home-assistant,代码行数:58,代码来源:core.py
示例8: __call__
def __call__(self, call):
"""Execute the service."""
try:
if self.schema:
call.data = self.schema(call.data)
self.func(call)
except vol.MultipleInvalid as ex:
_LOGGER.error('Invalid service data for %s.%s: %s',
call.domain, call.service,
humanize_error(call.data, ex))
开发者ID:MicSimoen,项目名称:home-assistant,代码行数:11,代码来源:core.py
示例9: _event_to_service_call
def _event_to_service_call(self, event):
"""Callback for SERVICE_CALLED events from the event bus."""
service_data = event.data.get(ATTR_SERVICE_DATA) or {}
domain = event.data.get(ATTR_DOMAIN).lower()
service = event.data.get(ATTR_SERVICE).lower()
call_id = event.data.get(ATTR_SERVICE_CALL_ID)
if not self.has_service(domain, service):
if event.origin == EventOrigin.local:
_LOGGER.warning("Unable to find service %s/%s",
domain, service)
return
service_handler = self._services[domain][service]
def fire_service_executed():
"""Fire service executed event."""
if not call_id:
return
data = {ATTR_SERVICE_CALL_ID: call_id}
if (service_handler.is_coroutinefunction or
service_handler.is_callback):
self._hass.bus.async_fire(EVENT_SERVICE_EXECUTED, data)
else:
self._hass.bus.fire(EVENT_SERVICE_EXECUTED, data)
try:
if service_handler.schema:
service_data = service_handler.schema(service_data)
except vol.Invalid as ex:
_LOGGER.error("Invalid service data for %s.%s: %s",
domain, service, humanize_error(service_data, ex))
fire_service_executed()
return
service_call = ServiceCall(domain, service, service_data, call_id)
if service_handler.is_callback:
service_handler.func(service_call)
fire_service_executed()
elif service_handler.is_coroutinefunction:
yield from service_handler.func(service_call)
fire_service_executed()
else:
def execute_service():
"""Execute a service and fires a SERVICE_EXECUTED event."""
service_handler.func(service_call)
fire_service_executed()
self._hass.async_add_job(execute_service)
开发者ID:arjenfvellinga,项目名称:home-assistant,代码行数:52,代码来源:core.py
示例10: auth_mfa_module_from_config
async def auth_mfa_module_from_config(
hass: HomeAssistant, config: Dict[str, Any]) \
-> MultiFactorAuthModule:
"""Initialize an auth module from a config."""
module_name = config[CONF_TYPE]
module = await _load_mfa_module(hass, module_name)
try:
config = module.CONFIG_SCHEMA(config) # type: ignore
except vol.Invalid as err:
_LOGGER.error('Invalid configuration for multi-factor module %s: %s',
module_name, humanize_error(config, err))
raise
return MULTI_FACTOR_AUTH_MODULES[module_name](hass, config) # type: ignore
开发者ID:ManHammer,项目名称:home-assistant,代码行数:15,代码来源:__init__.py
示例11: auth_provider_from_config
async def auth_provider_from_config(
hass: HomeAssistant, store: AuthStore,
config: Dict[str, Any]) -> AuthProvider:
"""Initialize an auth provider from a config."""
provider_name = config[CONF_TYPE]
module = await load_auth_provider_module(hass, provider_name)
try:
config = module.CONFIG_SCHEMA(config) # type: ignore
except vol.Invalid as err:
_LOGGER.error('Invalid configuration for auth provider %s: %s',
provider_name, humanize_error(config, err))
raise
return AUTH_PROVIDERS[provider_name](hass, store, config) # type: ignore
开发者ID:Martwall,项目名称:home-assistant,代码行数:15,代码来源:__init__.py
示例12: _log_exception
def _log_exception(ex, domain, config):
"""Generate log exception for config validation."""
message = 'Invalid config for [{}]: '.format(domain)
if 'extra keys not allowed' in ex.error_message:
message += '[{}] is an invalid option for [{}]. Check: {}->{}.'\
.format(ex.path[-1], domain, domain,
'->'.join('%s' % m for m in ex.path))
else:
message += humanize_error(config, ex)
if hasattr(config, '__line__'):
message += " (See {}:{})".format(config.__config_file__,
config.__line__ or '?')
_LOGGER.error(message)
开发者ID:hcchu,项目名称:home-assistant,代码行数:15,代码来源:bootstrap.py
示例13: auth_provider_from_config
async def auth_provider_from_config(hass, store, config):
"""Initialize an auth provider from a config."""
provider_name = config[CONF_TYPE]
module = await load_auth_provider_module(hass, provider_name)
if module is None:
return None
try:
config = module.CONFIG_SCHEMA(config)
except vol.Invalid as err:
_LOGGER.error('Invalid configuration for auth provider %s: %s',
provider_name, humanize_error(config, err))
return None
return AUTH_PROVIDERS[provider_name](hass, store, config)
开发者ID:keatontaylor,项目名称:home-assistant,代码行数:16,代码来源:__init__.py
示例14: post
def post(self, request):
"""Handle the POST request for device identification."""
try:
data = IDENTIFY_SCHEMA(request.json)
except vol.Invalid as ex:
return self.json_message(humanize_error(request.json, ex),
HTTP_BAD_REQUEST)
name = data.get(ATTR_DEVICE_ID)
CONFIG_FILE[ATTR_DEVICES][name] = data
if not _save_config(CONFIG_FILE_PATH, CONFIG_FILE):
return self.json_message("Error saving device.",
HTTP_INTERNAL_SERVER_ERROR)
return self.json({"status": "registered"})
开发者ID:krzynio,项目名称:home-assistant,代码行数:17,代码来源:ios.py
示例15: post
def post(self, request):
"""Accept the POST request for push registrations from a browser."""
try:
data = REGISTER_SCHEMA(request.json)
except vol.Invalid as ex:
return self.json_message(humanize_error(request.json, ex),
HTTP_BAD_REQUEST)
name = ensure_unique_string('unnamed device',
self.registrations.keys())
self.registrations[name] = data
if not _save_config(self.json_path, self.registrations):
return self.json_message('Error saving registration.',
HTTP_INTERNAL_SERVER_ERROR)
return self.json_message('Push notification subscriber registered.')
开发者ID:MicSimoen,项目名称:home-assistant,代码行数:18,代码来源:html5.py
示例16: test_humanize_error
def test_humanize_error():
data = {
'a': 'not an int',
'b': [123]
}
schema = Schema({
'a': int,
'b': [str]
})
try:
schema(data)
except MultipleInvalid as e:
assert_equal(
humanize_error(data, e),
"expected int for dictionary value @ data['a']. Got 'not an int'\n"
"expected str @ data['b'][0]. Got 123"
)
else:
assert False, 'Did not raise MultipleInvalid'
开发者ID:tuukkamustonen,项目名称:voluptuous,代码行数:19,代码来源:tests.py
示例17: _validate_docs_schema
def _validate_docs_schema(self, doc, schema, name, error_code):
# TODO: Add line/col
errors = []
try:
schema(doc)
except Exception as e:
for error in e.errors:
error.data = doc
errors.extend(e.errors)
for error in errors:
path = [str(p) for p in error.path]
if isinstance(error.data, dict):
error_message = humanize_error(error.data, error)
else:
error_message = error
self.reporter.error(
path=self.object_path,
code=error_code,
msg='%s.%s: %s' % (name, '.'.join(path), error_message)
)
开发者ID:ernstp,项目名称:ansible,代码行数:23,代码来源:main.py
示例18: async_handle
async def async_handle(self, msg):
"""Handle authentication."""
try:
msg = AUTH_MESSAGE_SCHEMA(msg)
except vol.Invalid as err:
error_msg = 'Auth message incorrectly formatted: {}'.format(
humanize_error(msg, err))
self._logger.warning(error_msg)
self._send_message(auth_invalid_message(error_msg))
raise Disconnect
if 'access_token' in msg:
self._logger.debug("Received access_token")
refresh_token = \
await self._hass.auth.async_validate_access_token(
msg['access_token'])
if refresh_token is not None:
return await self._async_finish_auth(
refresh_token.user, refresh_token)
elif self._hass.auth.support_legacy and 'api_password' in msg:
self._logger.info(
"Received api_password, it is going to deprecate, please use"
" access_token instead. For instructions, see https://"
"developers.home-assistant.io/docs/en/external_api_websocket"
".html#authentication-phase"
)
user = await legacy_api_password.async_validate_password(
self._hass, msg['api_password'])
if user is not None:
return await self._async_finish_auth(user, None)
self._send_message(auth_invalid_message(
'Invalid access token or password'))
await process_wrong_login(self._request)
raise Disconnect
开发者ID:boced66,项目名称:home-assistant,代码行数:36,代码来源:auth.py
示例19: handle
def handle(self, request):
"""Handle the websocket connection."""
wsock = self.wsock = web.WebSocketResponse()
yield from wsock.prepare(request)
self.debug("Connected")
# Get a reference to current task so we can cancel our connection
self._handle_task = asyncio.Task.current_task(loop=self.hass.loop)
@callback
def handle_hass_stop(event):
"""Cancel this connection."""
self.cancel()
unsub_stop = self.hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, handle_hass_stop)
self._writer_task = self.hass.async_add_job(self._writer())
final_message = None
msg = None
authenticated = False
try:
if request[KEY_AUTHENTICATED]:
authenticated = True
else:
yield from self.wsock.send_json(auth_required_message())
msg = yield from wsock.receive_json()
msg = AUTH_MESSAGE_SCHEMA(msg)
if validate_password(request, msg['api_password']):
authenticated = True
else:
self.debug("Invalid password")
yield from self.wsock.send_json(
auth_invalid_message('Invalid password'))
if not authenticated:
yield from process_wrong_login(request)
return wsock
yield from self.wsock.send_json(auth_ok_message())
# ---------- AUTH PHASE OVER ----------
msg = yield from wsock.receive_json()
last_id = 0
while msg:
self.debug("Received", msg)
msg = BASE_COMMAND_MESSAGE_SCHEMA(msg)
cur_id = msg['id']
if cur_id <= last_id:
self.to_write.put_nowait(error_message(
cur_id, ERR_ID_REUSE,
'Identifier values have to increase.'))
else:
handler_name = 'handle_{}'.format(msg['type'])
getattr(self, handler_name)(msg)
last_id = cur_id
msg = yield from wsock.receive_json()
except vol.Invalid as err:
error_msg = "Message incorrectly formatted: "
if msg:
error_msg += humanize_error(msg, err)
else:
error_msg += str(err)
self.log_error(error_msg)
if not authenticated:
final_message = auth_invalid_message(error_msg)
else:
if isinstance(msg, dict):
iden = msg.get('id')
else:
iden = None
final_message = error_message(
iden, ERR_INVALID_FORMAT, error_msg)
except TypeError as err:
if wsock.closed:
self.debug("Connection closed by client")
else:
self.log_error("Unexpected TypeError", msg)
except ValueError as err:
msg = "Received invalid JSON"
value = getattr(err, 'doc', None) # Py3.5+ only
if value:
msg += ': {}'.format(value)
self.log_error(msg)
self._writer_task.cancel()
#.........这里部分代码省略.........
开发者ID:Khabi,项目名称:home-assistant,代码行数:101,代码来源:websocket_api.py
示例20: handle
def handle(self):
"""Handle the websocket connection."""
wsock = self.wsock = web.WebSocketResponse()
yield from wsock.prepare(self.request)
# Set up to cancel this connection when Home Assistant shuts down
socket_task = asyncio.Task.current_task(loop=self.hass.loop)
@callback
def cancel_connection(event):
"""Cancel this connection."""
socket_task.cancel()
unsub_stop = self.hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP,
cancel_connection)
self.debug('Connected')
msg = None
authenticated = False
try:
if self.request[KEY_AUTHENTICATED]:
authenticated = True
else:
self.send_message(auth_required_message())
msg = yield from wsock.receive_json()
msg = AUTH_MESSAGE_SCHEMA(msg)
if validate_password(self.request, msg['api_password']):
authenticated = True
else:
self.debug('Invalid password')
self.send_message(auth_invalid_message('Invalid password'))
if not authenticated:
yield from process_wrong_login(self.request)
return wsock
self.send_message(auth_ok_message())
msg = yield from wsock.receive_json()
last_id = 0
while msg:
self.debug('Received', msg)
msg = BASE_COMMAND_MESSAGE_SCHEMA(msg)
cur_id = msg['id']
if cur_id <= last_id:
self.send_message(error_message(
cur_id, ERR_ID_REUSE,
'Identifier values have to increase.'))
else:
handler_name = 'handle_{}'.format(msg['type'])
getattr(self, handler_name)(msg)
last_id = cur_id
msg = yield from wsock.receive_json()
except vol.Invalid as err:
error_msg = 'Message incorrectly formatted: '
if msg:
error_msg += humanize_error(msg, err)
else:
error_msg += str(err)
self.log_error(error_msg)
if not authenticated:
self.send_message(auth_invalid_message(error_msg))
else:
if isinstance(msg, dict):
iden = msg.get('id')
else:
iden = None
self.send_message(error_message(iden, ERR_INVALID_FORMAT,
error_msg))
except TypeError as err:
if wsock.closed:
self.debug('Connection closed by client')
else:
self.log_error('Unexpected TypeError', msg)
except ValueError as err:
msg = 'Received invalid JSON'
value = getattr(err, 'doc', None) # Py3.5+ only
if value:
msg += ': {}'.format(value)
self.log_error(msg)
except asyncio.CancelledError:
self.debug('Connection cancelled by server')
#.........这里部分代码省略.........
开发者ID:azogue,项目名称:home-assistant,代码行数:101,代码来源:websocket_api.py
注:本文中的voluptuous.humanize.humanize_error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论