本文整理汇总了Python中six.raise_from方法的典型用法代码示例。如果您正苦于以下问题:Python six.raise_from方法的具体用法?Python six.raise_from怎么用?Python six.raise_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six
的用法示例。
在下文中一共展示了six.raise_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = ''.join(self.source)
try:
compile(src, filename, 'exec')
except SyntaxError as error:
six.raise_from(ParseError(), error)
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.all = None
self.future_imports = set()
self._accumulated_decorators = []
return self.parse_module()
# TODO: remove
示例2: _takes_ascii
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def _takes_ascii(f):
@wraps(f)
def func(self, str_in, *args, **kwargs):
# If it's a stream, read the whole thing
str_in = getattr(str_in, 'read', lambda: str_in)()
# If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII
if isinstance(str_in, six.text_type):
# ASCII is the same in UTF-8
try:
str_in = str_in.encode('ascii')
except UnicodeEncodeError as e:
msg = 'ISO-8601 strings should contain only ASCII characters'
six.raise_from(ValueError(msg), e)
return f(self, str_in, *args, **kwargs)
return func
示例3: get
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def get(self, profile_id):
'''Returns the profile with the received ID as a dict
If a local copy of the profile exists, it'll be returned. If not, it'll
be downloaded from the web. The results are cached, so any subsequent
calls won't hit the filesystem or the web.
Args:
profile_id (str): The ID of the profile you want.
Raises:
RegistryError: If there was some problem opening the profile file
or its format was incorrect.
'''
if profile_id not in self._profiles:
try:
self._profiles[profile_id] = self._get_profile(profile_id)
except (ValueError,
IOError) as e:
six.raise_from(RegistryError(e), e)
return self._profiles[profile_id]
# Internal
示例4: _get_registry
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def _get_registry(self, registry_path_or_url):
'''dict: Return the registry as dict with profiles keyed by id.'''
if registry_path_or_url.startswith('http'):
profiles = self._load_json_url(registry_path_or_url)
else:
profiles = self._load_json_file(registry_path_or_url)
try:
registry = {}
for profile in profiles:
registry[profile['id']] = profile
return registry
except KeyError as e:
msg = (
'Registry at "{path}" has no "id" column.'
).format(path=registry_path_or_url)
six.raise_from(ValueError(msg), e)
示例5: read
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def read(self, size):
while len(self.buffer) < size:
self.ensure_connection()
try:
packet = self.socket.recv(self.buffer_size)
except socket.error as error:
if error.errno in (EDEADLK, EAGAIN, EWOULDBLOCK):
gevent.sleep()
continue
six.raise_from(NSQSocketError(*error.args), error)
if not packet:
self.close()
self.buffer += packet
data = self.buffer[:size]
self.buffer = self.buffer[size:]
return data
示例6: upgrade_to_tls
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def upgrade_to_tls(
self,
keyfile=None,
certfile=None,
cert_reqs=CERT_NONE,
ca_certs=None,
ssl_version=PROTOCOL_TLSv1_2
):
self.ensure_connection()
try:
self.socket = SSLSocket(
self.socket,
keyfile=keyfile,
certfile=certfile,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
ssl_version=ssl_version,
)
except socket.error as error:
six.raise_from(NSQSocketError(*error.args), error)
示例7: assert_called_with
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def assert_called_with(_mock_self, *args, **kwargs):
"""assert that the mock was called with the specified arguments.
Raises an AssertionError if the args and keyword args passed in are
different to the last call to the mock."""
self = _mock_self
if self.call_args is None:
expected = self._format_mock_call_signature(args, kwargs)
raise AssertionError('Expected call: %s\nNot called' % (expected,))
def _error_message(cause):
msg = self._format_mock_failure_message(args, kwargs)
if six.PY2 and cause is not None:
# Tack on some diagnostics for Python without __cause__
msg = '%s\n%s' % (msg, str(cause))
return msg
expected = self._call_matcher((args, kwargs))
actual = self._call_matcher(self.call_args)
if expected != actual:
cause = expected if isinstance(expected, Exception) else None
six.raise_from(AssertionError(_error_message(cause)), cause)
示例8: wrap_exception
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def wrap_exception(self, event_args, *args, **kwargs):
next_handler = event_args.pop("next_handler")
if not next_handler:
return
try:
return next_handler.invoke(event_args, *args, **kwargs)
except Exception as e:
if isinstance(e, CloudBridgeBaseException):
raise
else:
ex_type, ex_value, traceback = sys.exc_info()
cb_ex = CloudBridgeBaseException(
"CloudBridgeBaseException: {0} from exception type: {1}"
.format(ex_value, ex_type))
if sys.version_info >= (3, 0):
six.raise_from(cb_ex, e)
else:
six.reraise(CloudBridgeBaseException, cb_ex, traceback)
示例9: _to_decimal
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def _to_decimal(self, val):
try:
decimal_value = Decimal(val)
# See GH 662, edge case, infinite value should not be converted
# via `_to_decimal`
if not decimal_value.is_finite():
raise ValueError("Converted decimal value is infinite or NaN")
except Exception as e:
msg = "Could not convert %s to decimal" % val
six.raise_from(ValueError(msg), e)
else:
return decimal_value
# ------------------------------------------------------------------
# Post-Parsing construction of datetime output. These are kept as
# methods instead of functions for the sake of customizability via
# subclassing.
示例10: refresh
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def refresh(self, request):
"""Refresh the access token and scopes.
Args:
request (google.auth.transport.Request): The object used to make
HTTP requests.
Raises:
google.auth.exceptions.RefreshError: If the Compute Engine metadata
service can't be reached if if the instance has not
credentials.
"""
try:
self._retrieve_info(request)
self.token, self.expiry = _metadata.get_service_account_token(
request, service_account=self._service_account_email
)
except exceptions.TransportError as caught_exc:
new_exc = exceptions.RefreshError(caught_exc)
six.raise_from(new_exc, caught_exc)
示例11: _read_dca_metadata_file
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def _read_dca_metadata_file(metadata_path):
"""Loads context aware metadata from the given path.
Args:
metadata_path (str): context aware metadata path.
Returns:
Dict[str, str]: The metadata.
Raises:
google.auth.exceptions.ClientCertError: If failed to parse metadata as JSON.
"""
try:
with open(metadata_path) as f:
metadata = json.load(f)
except ValueError as caught_exc:
new_exc = exceptions.ClientCertError(caught_exc)
six.raise_from(new_exc, caught_exc)
return metadata
示例12: ingest_killmail
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def ingest_killmail(self, json_response):
# zKillboard has the ability to return multiple killmails in one API
# response, so the response is an array of killmail objects, while ESI
# only returns one killmail per response.
try:
killmail_json = json_response[0]
except IndexError as idx_exc:
val_exc = ValueError(gettext(u"'%(url)s' is not a valid %(source)s"
u" killmail.",
source=self.killmail_source,
url=self.url))
six.raise_from(val_exc, idx_exc)
super(ZKillmail, self).ingest_killmail(killmail_json)
# Continue on and add some zKB-specific info
# TODO: customize JSON parser to pull out these values as decimals, not
# floats
self.value = Decimal(killmail_json[u'zkb'][u'totalValue'])
# Backwards compatibility
示例13: _handle_error
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def _handle_error(self, err):
"""
Handle execution error state and sleep the required amount of time.
"""
# Update latest cached error
self.error = err
# Defaults to false
retry = True
# Evaluate if error is legit or should be retried
if self.error_evaluator:
retry = self.error_evaluator(err)
# If evalutor returns an error exception, just raise it
if retry and isinstance(retry, Exception):
raise_from(retry, self.error)
# If retry evaluator returns False, raise original error and
# stop the retry cycle
if retry is False:
raise err
示例14: augment_exception_message_and_reraise
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def augment_exception_message_and_reraise(exception, message):
"""Reraises `exception`, appending `message` to its string representation."""
class ExceptionProxy(type(exception)):
"""Acts as a proxy for an exception with an augmented message."""
__module__ = type(exception).__module__
def __init__(self):
pass
def __getattr__(self, attr_name):
return getattr(exception, attr_name)
def __str__(self):
return str(exception) + message
ExceptionProxy.__name__ = type(exception).__name__
proxy = ExceptionProxy()
if six.PY3:
ExceptionProxy.__qualname__ = type(exception).__qualname__
six.raise_from(proxy.with_traceback(exception.__traceback__), None)
else:
six.reraise(proxy, None, sys.exc_info()[2])
示例15: infer_output_definitions
# 需要导入模块: import six [as 别名]
# 或者: from six import raise_from [as 别名]
def infer_output_definitions(decorator_name, solid_name, fn):
signature = funcsigs.signature(fn)
try:
return [
OutputDefinition()
if signature.return_annotation is funcsigs.Signature.empty
else OutputDefinition(signature.return_annotation)
]
except CheckError as type_error:
six.raise_from(
DagsterInvalidDefinitionError(
'Error inferring Dagster type for return type '
'"{type_annotation}" from {decorator} "{solid}". '
'Correct the issue or explicitly pass definitions to {decorator}.'.format(
decorator=decorator_name,
solid=solid_name,
type_annotation=signature.return_annotation,
)
),
type_error,
)