本文整理汇总了Python中six.raise_from函数的典型用法代码示例。如果您正苦于以下问题:Python raise_from函数的具体用法?Python raise_from怎么用?Python raise_from使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了raise_from函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_bytes
def to_bytes(proto, string):
try:
return struct.pack('>H', int(string, 10))
except ValueError as exc:
six.raise_from(ValueError("Not a base 10 integer"), exc)
except struct.error as exc:
six.raise_from(ValueError("Integer not in range(65536)"), exc)
示例2: save
def save(self):
parent_product = self.parent_product
current_products = set(parent_product.get_package_child_to_quantity_map())
selected_products, removed_products, selected_quantities = self.get_selected_and_removed()
with atomic():
try:
clear_existing_package(parent_product)
parent_product.make_package(package_def=selected_quantities)
except ImpossibleProductModeException as ipme:
six.raise_from(
Problem(
_("Unable to make package %(product)s: %(error)s") %
{"product": parent_product, "error": ipme}
), ipme
)
products_to_add = selected_products - current_products
products_to_remove = current_products & removed_products
message_parts = []
if products_to_add:
message_parts.append(_("New: %d") % len(products_to_add))
if products_to_remove:
message_parts.append(_("Removed: %d") % len(products_to_remove))
if message_parts and self.request:
messages.success(self.request, ", ".join(message_parts))
示例3: validate_plan
def validate_plan(self, plan_name):
"""Validate Plan
This private method provides validations to ensure a plan
meets the proper criteria before allowed to persist in storage.
:param plan_files: The files to import into the container.
:type plan_files: dict
:returns boolean
"""
plan = self.get_plan(plan_name)
# there can only be up to one root-template file in metadata
rt = {k: v for (k, v) in plan.files.items()
if v.get('meta', {}).get('file-type') == 'root-template'}
if len(rt) > 1:
raise exception.TooManyRootTemplatesError()
# the plan needs to be validated with heat to ensure it conforms
template, environment, files = templates.process_plan_data(plan.files)
try:
self.heatclient.stacks.validate(
template=template,
files=files,
environment=environment,
show_nested=True)
except heatexceptions.HTTPBadRequest as exc:
LOG.exception("Error validating the plan.")
six.raise_from(exception.HeatValidationFailedError(msg=exc), exc)
# no validation issues found
return True
示例4: wait_until_render_complete
def wait_until_render_complete(driver):
'''
'''
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
def is_bokeh_loaded(driver):
return driver.execute_script('''
const b = window.Bokeh;
return b && b.documents && b.documents.length > 0;
''')
try:
WebDriverWait(driver, 5, poll_frequency=0.1).until(is_bokeh_loaded)
except TimeoutException as e:
raise_from(RuntimeError('Bokeh was not loaded in time. Something may have gone wrong.'), e)
driver.execute_script(_WAIT_SCRIPT)
def is_bokeh_render_complete(driver):
return driver.execute_script('return window._bokeh_render_complete;')
try:
WebDriverWait(driver, 5, poll_frequency=0.1).until(is_bokeh_render_complete)
except TimeoutException:
log.warn("The webdriver raised a TimeoutException while waiting for \
a 'bokeh:idle' event to signify that the layout has rendered. \
Something may have gone wrong.")
finally:
browser_logs = driver.get_log('browser')
severe_errors = [l for l in browser_logs if l.get('level') == 'SEVERE']
if len(severe_errors) > 0:
log.warn("There were severe browser errors that may have affected your export: {}".format(severe_errors))
示例5: convert
def convert(credentials):
"""Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.service_account.ServiceAccountCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.service_account._JWTAccessCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
:class:`google.auth.compute_engine.Credentials`.
- :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
:class:`google.auth.app_engine.Credentials`.
Returns:
google.auth.credentials.Credentials: The converted credentials.
Raises:
ValueError: If the credentials could not be converted.
"""
credentials_class = type(credentials)
try:
return _CLASS_CONVERSION_MAP[credentials_class](credentials)
except KeyError as caught_exc:
new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
six.raise_from(new_exc, caught_exc)
示例6: _get
def _get(self, *args, **kwargs):
try:
response = self._session.get(*args, **kwargs)
response.raise_for_status()
except requests.RequestException as e:
six.raise_from(NetworkError, e)
return response
示例7: parse_sentence
def parse_sentence(self, text):
"""
Takes a Tanaka corpus formatted sentence and parses it into tagged
:class:`TatoebaIndexReader.WordClass` (by default :class:`TanakaWord`)
word objects.
:param text:
A Tanaka-corpus formatted sentence.
:return:
Returns a :py:class:`list` of :class:`TatoebaIndexReader.WordClass`
objects representing a given sentence.
"""
words = self.sentence_splitter(text)
sentence = []
for word in words:
if not len(word):
continue
try:
wobj = self.WordClass.from_text(word)
except InvalidEntryError as e:
msg = u'Failed to interpret word {w} in sentence {s}'
raise_from(InvalidEntryError(msg.format(w=word, s=text)), e)
sentence.append(wobj)
return sentence
示例8: _config_line_directories_section
def _config_line_directories_section(self, line, line_no):
"""Called for each line in the directories section
line is in one of 3 formats:
= <new directory list>
- <remove directory list>
+ <additional directory list
:param line: The full line from the config file
:param line_no : The line number in the config file
:raises ConfigError: When an invalid line is detected
"""
# Extract Attribute name from the config sections data
attr_name = \
self.config_sections_and_attrs['directories']['directories'][0]
op, direct = line[0], set(
d.strip() for d in line[1:].strip().split(','))
direct = direct if direct != {''} else set()
if direct:
# Identify null strings or strings which are just dots
if any(d == '' for d in direct):
six.raise_from(ConfigError(
'Invalid value in [directories] section :'
' \'{}\' on line {}'.format(
line, line_no)), None)
self._config_operator_list_modifiers(
attr_name, direct, line, line_no, op, 'directories')
示例9: _config_line_extensions_section
def _config_line_extensions_section(self, line, line_no):
"""Called for each line in the extensions section
line is in one of 3 formats:
= <new directory list>
- <remove directory list>
+ <additional directory list
:param line: The full line from the config file
:param line_no : The line number in the config file
"""
# Extract Attribute name from the config sections data
section_data = self.config_sections_and_attrs['extensions']
attr_name = section_data['extensions'][0]
op, ext = line[0], set(e.strip() for e in line[1:].strip().split(','))
ext = ext if ext != {''} else set()
if ext:
# Identify null strings or strings which are just dots
if any(len(e) <= 1 for e in ext):
six.raise_from(ConfigError(
'Invalid value in [extension] section :'
' \'{}\' on line {}'.format(
line, line_no)), None)
# Identify extension values without a leading dot
if any(e[0] != '.' for e in ext):
six.raise_from(ConfigError(
'Invalid value in [extension] section :'
' \'{}\' on line {}'.format(
line, line_no)), None)
self._config_operator_list_modifiers(
attr_name, ext, line, line_no, op, 'extension')
示例10: acquire
def acquire(self):
"""
Attempt to acquire the lock.
If the lock is successfully acquired, this method returns a context
manager that will automatically release the lock when exited. If the
lock cannot be acquired, an ``UnableToAcquireLock`` error will be
raised.
"""
try:
self.backend.acquire(self.key, self.duration, self.routing_key)
except Exception as error:
six.raise_from(
UnableToAcquireLock('Unable to acquire {!r} due to error: {}'.format(self, error)),
error
)
@contextmanager
def releaser():
try:
yield
finally:
self.release()
return releaser()
示例11: _config_line_reports_section
def _config_line_reports_section(self, line, line_no):
"""Called for each line in the directories section
line is in one of 3 formats:
= <new directory list>
- <remove directory list>
+ <additional directory list
:param line: The full line from the config file
:param line_no : The line number in the config file
:raises ConfigError: When an invalid line is detected"""
attrs_options = self.config_sections_and_attrs['reports']
try:
option, _, value = (x.strip() for x in line.partition('='))
if option != 'verbose':
value = value.lower() in ['true', 'yes']
else:
try:
value = int(value)
except ValueError:
six.raise_from(ConfigError(
'Invalid value in section [reports] :'
' \'{}\' on line {}'.format(
line, line_no)), None)
setattr(self, attrs_options[option][0], value)
except KeyError:
six.raise_from(ConfigError(
'Invalid option in section [reports] :'
' \'{}\' on line {}'.format(
line, line_no)), None)
示例12: get_changes
def get_changes(self, resource):
if resource not in self.changes:
try:
self.changes[resource] = list(self.get_plan(resource).get_actions())
except Exception as e:
six.raise_from(errors.Error("{}: {}".format(resource, e)), e)
return self.changes[resource]
示例13: _load_schema
def _load_schema(self, schema, registry):
the_schema = schema
if isinstance(schema, six.string_types):
try:
the_schema = registry.get(schema)
if not the_schema:
if os.path.isfile(schema):
with open(schema, 'r') as f:
the_schema = json.load(f)
else:
req = requests.get(schema)
req.raise_for_status()
the_schema = req.json()
except (IOError, ValueError, requests.exceptions.RequestException) as ex:
message = 'Unable to load profile at "{0}"'
six.raise_from(
exceptions.ValidationError(message.format(schema)),
ex
)
elif isinstance(the_schema, dict):
the_schema = copy.deepcopy(the_schema)
else:
message = 'Schema must be a "dict", but was a "{0}"'
raise exceptions.ValidationError(message.format(type(the_schema).__name__))
return the_schema
示例14: raise_with_cause
def raise_with_cause(exc_cls, message, *args, **kwargs):
"""Helper to raise + chain exceptions (when able) and associate a *cause*.
NOTE(harlowja): Since in py3.x exceptions can be chained (due to
:pep:`3134`) we should try to raise the desired exception with the given
*cause* (or extract a *cause* from the current stack if able) so that the
exception formats nicely in old and new versions of python. Since py2.x
does **not** support exception chaining (or formatting) the exception
class provided should take a ``cause`` keyword argument (which it may
discard if it wants) to its constructor which can then be
inspected/retained on py2.x to get *similar* information as would be
automatically included/obtainable in py3.x.
:param exc_cls: the exception class to raise (typically one derived
from :py:class:`.CausedByException` or equivalent).
:param message: the text/str message that will be passed to
the exceptions constructor as its first positional
argument.
:param args: any additional positional arguments to pass to the
exceptions constructor.
:param kwargs: any additional keyword arguments to pass to the
exceptions constructor.
.. versionadded:: 1.6
"""
if 'cause' not in kwargs:
exc_type, exc, exc_tb = sys.exc_info()
try:
if exc is not None:
kwargs['cause'] = exc
finally:
# Leave no references around (especially with regards to
# tracebacks and any variables that it retains internally).
del(exc_type, exc, exc_tb)
six.raise_from(exc_cls(message, *args, **kwargs), kwargs.get('cause'))
示例15: __call__
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request using requests.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
requests default timeout will be used.
kwargs: Additional arguments passed through to the underlying
requests :meth:`~requests.Session.request` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
try:
_LOGGER.debug('Making request: %s %s', method, url)
response = self.session.request(
method, url, data=body, headers=headers, timeout=timeout,
**kwargs)
return _Response(response)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)