本文整理汇总了Python中six.reraise函数的典型用法代码示例。如果您正苦于以下问题:Python reraise函数的具体用法?Python reraise怎么用?Python reraise使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了reraise函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: reraise_as
def reraise_as(new_exception_or_type):
"""
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py
>>> try:
>>> do_something_crazy()
>>> except Exception:
>>> reraise_as(UnhandledException)
"""
__traceback_hide__ = True # NOQA
e_type, e_value, e_traceback = sys.exc_info()
if inspect.isclass(new_exception_or_type):
new_type = new_exception_or_type
new_exception = new_exception_or_type()
else:
new_type = type(new_exception_or_type)
new_exception = new_exception_or_type
new_exception.__cause__ = e_value
try:
six.reraise(new_type, new_exception, e_traceback)
finally:
del e_traceback
开发者ID:wanghe4096,项目名称:WangBlog,代码行数:25,代码来源:settings.py
示例2: __call__
def __call__(self, request):
"""WSGI method that controls (de)serialization and method dispatch."""
action_args = self.get_action_args(request.environ)
action = action_args.pop('action', None)
try:
deserialized_request = self.dispatch(self.deserializer,
action, request)
action_args.update(deserialized_request)
action_result = self.dispatch(self.controller, action,
request, **action_args)
except webob.exc.WSGIHTTPException as e:
exc_info = sys.exc_info()
six.reraise(translate_exception(request, e), None, exc_info[2])
try:
response = webob.Response(request=request)
self.dispatch(self.serializer, action, response, action_result)
return response
except webob.exc.WSGIHTTPException as e:
return translate_exception(request, e)
except webob.exc.HTTPException as e:
return e
# return unserializable result (typically a webob exc)
except Exception:
return action_result
开发者ID:ianunruh,项目名称:glance,代码行数:26,代码来源:wsgi.py
示例3: start_response
def start_response(status, headers, exc_info=None):
if task.wroteResponseHeader() and not exc_info:
raise AssertionError("start_response called a second time "
"without providing exc_info.")
if exc_info:
try:
if task.wroteResponseHeader():
# higher levels will catch and handle raised exception:
# 1. "service" method in httptask.py
# 2. "service" method in severchannelbase.py
# 3. "handlerThread" method in taskthreads.py
six.reraise(*exc_info)
else:
# As per WSGI spec existing headers must be cleared
task.accumulated_headers = None
task.response_headers = {}
finally:
exc_info = None
# Prepare the headers for output
status, reason = re.match('([0-9]*) (.*)', status).groups()
task.setResponseStatus(status, reason)
task.appendResponseHeaders(['%s: %s' % i for i in headers])
# Return the write method used to write the response data.
return fakeWrite
开发者ID:zopefoundation,项目名称:zope.server,代码行数:25,代码来源:wsgihttpserver.py
示例4: import_string
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
from django.utils.module_loading import import_string
return import_string(dotted_path)
except ImportError:
pass
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
dotted_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
开发者ID:pedfercue,项目名称:django-chroniker,代码行数:26,代码来源:utils.py
示例5: xpath
def xpath(self, query):
"""
Find nodes matching the xpath ``query`` and return the result as a
:class:`SelectorList` instance with all elements flattened. List
elements implement :class:`Selector` interface too.
``query`` is a string containing the XPATH query to apply.
"""
try:
xpathev = self.root.xpath
except AttributeError:
return self.selectorlist_cls([])
try:
result = xpathev(query, namespaces=self.namespaces,
smart_strings=self._lxml_smart_strings)
except etree.XPathError as exc:
msg = u"XPath error: %s in %s" % (exc, query)
msg = msg if six.PY3 else msg.encode('unicode_escape')
six.reraise(ValueError, ValueError(msg), sys.exc_info()[2])
if type(result) is not list:
result = [result]
result = [self.__class__(root=x, _expr=query,
namespaces=self.namespaces,
type=self.type)
for x in result]
return self.selectorlist_cls(result)
开发者ID:BarnetteME1,项目名称:indeed_scraper,代码行数:29,代码来源:selector.py
示例6: write
def write(self, stream):
# now, pack everything in
crc_fields = []
for name, field in self.ordered_fields:
try:
if isinstance(field, CRCField):
crc_offset = stream.tell()
field.pack(stream)
crc_fields.append((field, crc_offset))
else:
field.pack(stream)
except SuitcaseException:
raise # just reraise the same exception object
except Exception:
# keep the original traceback information, see
# http://stackoverflow.com/questions/3847503/wrapping-exceptions-in-python
exc_value = SuitcasePackException("Unexpected exception during pack of %r" % name)
six.reraise(type(exc_value), exc_value, sys.exc_info()[2])
# if there is a crc value, seek back to the field and
# pack it with the right value
if len(crc_fields) > 0:
data = stream.getvalue()
for field, offset in crc_fields:
stream.seek(offset)
checksum_data = self.crc_field.packed_checksum(data)
stream.write(checksum_data)
开发者ID:rcfox,项目名称:python-suitcase,代码行数:27,代码来源:structure.py
示例7: run_with_timeout_and_stack
def run_with_timeout_and_stack(request, timeout):
'''
interrupts evaluation after a given time period. provides a suitable stack environment.
'''
# only use set_thread_stack_size if max recursion depth was changed via the environment variable
# MATHICS_MAX_RECURSION_DEPTH. if it is set, we always use a thread, even if timeout is None, in
# order to be able to set the thread stack size.
if MAX_RECURSION_DEPTH > settings.DEFAULT_MAX_RECURSION_DEPTH:
set_thread_stack_size(python_stack_size(MAX_RECURSION_DEPTH))
elif timeout is None:
return request()
queue = Queue(maxsize=1) # stores the result or exception
thread = Thread(target=_thread_target, args=(request, queue))
thread.start()
thread.join(timeout)
if thread.is_alive():
raise TimeoutInterrupt()
success, result = queue.get()
if success:
return result
else:
six.reraise(*result)
开发者ID:mathics,项目名称:Mathics,代码行数:27,代码来源:evaluation.py
示例8: get
def get(self):
"""Creates a generator to extract data from the queue.
Skip the data if it is `None`.
# Yields
The next element in the queue, i.e. a tuple
`(inputs, targets)` or
`(inputs, targets, sample_weights)`.
"""
try:
while self.is_running():
try:
future = self.queue.get(block=True)
inputs = future.get(timeout=30)
self.queue.task_done()
except mp.TimeoutError:
idx = future.idx
warnings.warn(
'The input {} could not be retrieved.'
' It could be because a worker has died.'.format(idx),
UserWarning)
inputs = self.sequence[idx]
if inputs is not None:
yield inputs
except Exception:
self.stop()
six.reraise(*sys.exc_info())
开发者ID:TNonet,项目名称:keras,代码行数:28,代码来源:data_utils.py
示例9: add_paths
def add_paths(self, paths=None):
"""
Adds the paths defined in the specification as endpoints
:type paths: list
"""
paths = paths or self.specification.get('paths', dict())
for path, methods in paths.items():
logger.debug('Adding %s%s...', self.base_url, path)
# search for parameters definitions in the path level
# http://swagger.io/specification/#pathItemObject
path_parameters = methods.get('parameters', [])
# TODO Error handling
for method, endpoint in methods.items():
if method == 'parameters':
continue
try:
self.add_operation(method, path, endpoint, path_parameters)
except Exception: # pylint: disable= W0703
url = '{base_url}{path}'.format(base_url=self.base_url,
path=path)
error_msg = 'Failed to add operation for {method} {url}'.format(
method=method.upper(),
url=url)
if self.debug:
logger.exception(error_msg)
else:
logger.error(error_msg)
six.reraise(*sys.exc_info())
开发者ID:flabe81,项目名称:connexion,代码行数:31,代码来源:api.py
示例10: __init__
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
if 'code' not in self.kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
if not message:
try:
message = self.msg_fmt % kwargs
except Exception:
exc_info = sys.exc_info()
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation'))
for name, value in six.iteritems(kwargs):
LOG.error("%s: %s" % (name, value)) # noqa
if CONF.fatal_exception_format_errors:
six.reraise(*exc_info)
else:
# at least get the core message out if something happened
message = self.msg_fmt
self.message = message
super(JacketException, self).__init__(message)
开发者ID:HybridF5,项目名称:jacket,代码行数:29,代码来源:exception.py
示例11: load_from_dir
def load_from_dir(source_directory, filename='manifest.yaml'):
if not os.path.isdir(source_directory) or not os.path.exists(
source_directory):
raise e.PackageLoadError('Invalid package directory')
full_path = os.path.join(source_directory, filename)
if not os.path.isfile(full_path):
raise e.PackageLoadError('Unable to find package manifest')
try:
with open(full_path) as stream:
content = yaml.safe_load(stream)
except Exception as ex:
trace = sys.exc_info()[2]
six.reraise(
e.PackageLoadError,
e.PackageLoadError("Unable to load due to '{0}'".format(ex)),
trace)
else:
format_spec = str(content.get('Format') or 'MuranoPL/1.0')
if format_spec[0].isdigit():
format_spec = 'MuranoPL/' + format_spec
plugin_loader = get_plugin_loader()
handler = plugin_loader.get_package_handler(format_spec)
if handler is None:
raise e.PackageFormatError(
'Unsupported format {0}'.format(format_spec))
return handler(source_directory, content)
开发者ID:Aqsamm,项目名称:murano,代码行数:27,代码来源:load_utils.py
示例12: set_data_for_a_field
def set_data_for_a_field(self, model_class, __instance, __field, locators, persist_dependencies=True, **kwargs):
if __field.name in kwargs:
config = kwargs[__field.name]
try:
data = self._process_field_with_customized_fixture(__instance, __field, config, persist_dependencies)
except PendingField:
return # ignore this field for a while.
except Exception as e:
six.reraise(InvalidConfigurationError, InvalidConfigurationError(get_unique_field_name(__field), e), sys.exc_info()[2])
else:
data = self._process_field_with_default_fixture(__field, model_class, persist_dependencies, locators)
if is_file_field(__field) and data:
django_file = data
if isinstance(django_file, File):
setattr(__instance, __field.name, data.name) # set the attribute
if django_file.file.mode != 'rb':
django_file.file.close() # this file may be open in another mode, for example, in a+b
opened_file = open(django_file.file.name, 'rb') # to save the file it must be open in rb mode
django_file.file = opened_file # we update the reference to the rb mode opened file
getattr(__instance, __field.name).save(django_file.name, django_file) # save the file into the file storage system
django_file.close()
else: # string (saving just a name in the file, without saving the file to the storage file system
setattr(__instance, __field.name, data) # Model.field = data
else:
if self.debug_mode:
LOGGER.debug('%s.%s = %s' % (get_unique_model_name(model_class), __field.name, data))
setattr(__instance, __field.name, data) # Model.field = data
self.fields_processed.append(__field.name)
开发者ID:slensgra,项目名称:db_populator,代码行数:29,代码来源:ddf.py
示例13: wrapped
def wrapped(*args, **kwargs):
sleep_time = self._sleep_factor
exc_info = None
for attempt in range(self._count):
if attempt != 0:
LOG.warning(_LW('Retrying failed call to %(func)s, '
'attempt %(attempt)i.'),
{'func': func_name,
'attempt': attempt})
try:
return fun(*args, **kwargs)
except self._exceptions:
exc_info = sys.exc_info()
if attempt != self._count - 1:
if self._sleep_mechanism == self.SLEEP_NONE:
continue
elif self._sleep_mechanism == self.SLEEP_INCREMENT:
time.sleep(sleep_time)
sleep_time += self._sleep_factor
elif self._sleep_mechanism == self.SLEEP_DOUBLE:
time.sleep(sleep_time)
sleep_time *= 2
else:
raise ValueError('Unknown sleep mechanism: %r'
% self._sleep_mechanism)
six.reraise(exc_info[0], exc_info[1], exc_info[2])
开发者ID:kaitlin-farr,项目名称:cinder,代码行数:29,代码来源:srb.py
示例14: _check_failure_status
def _check_failure_status(self):
""" Check the status of command failures. Raise exceptions as necessary
The failure status property is used by the various asynchronous
command execution threads which interface with the
remote browser manager processes. If a failure status is found, the
appropriate steps are taken to gracefully close the infrastructure
"""
self.logger.debug("Checking command failure status indicator...")
if self.failure_status:
self.logger.debug(
"TaskManager failure status set, halting command execution.")
self._cleanup_before_fail()
if self.failure_status['ErrorType'] == 'ExceedCommandFailureLimit':
raise CommandExecutionError(
"TaskManager exceeded maximum consecutive command "
"execution failures.",
self.failure_status['CommandSequence']
)
elif (self.failure_status['ErrorType'] == ("ExceedLaunch"
"FailureLimit")):
raise CommandExecutionError(
"TaskManager failed to launch browser within allowable "
"failure limit.", self.failure_status['CommandSequence']
)
if self.failure_status['ErrorType'] == 'CriticalChildException':
reraise(*pickle.loads(self.failure_status['Exception']))
开发者ID:gunesacar,项目名称:OpenWPM,代码行数:27,代码来源:TaskManager.py
示例15: value
def value(self):
"""Get parameter value.
If this cached value is None and this serialized value is not None,
calculate the new value from the serialized one.
:return: parameter value.
:raises: TypeError if serialized value is not an instance of self ptype
. ParserError if parsing step raised an error.
"""
result = self._value
if result is None and self._svalue is not None:
try:
result = self._value = self.resolve()
except Exception as e:
reraise(
Parameter.Error,
Parameter.Error('Call the method "resolve" first.')
)
return result
开发者ID:b3j0f,项目名称:conf,代码行数:25,代码来源:param.py
示例16: MultiProcFailCheck
def MultiProcFailCheck():
""" Wrap this around code that you want to globally fail if it fails
on any MPI process in MPI_WORLD. If not running under MPI, don't
handle any exceptions.
"""
if MPI is None:
yield
else:
try:
yield
except:
exc_type, exc_val, exc_tb = sys.exc_info()
if exc_val is not None:
fail = True
else:
fail = False
fails = MPI.COMM_WORLD.allgather(fail)
if fail or not any(fails):
six.reraise(exc_type, exc_val, exc_tb)
else:
for i, f in enumerate(fails):
if f:
raise RuntimeError("a test failed in (at least) rank %d" % i)
开发者ID:imclab,项目名称:OpenMDAO,代码行数:25,代码来源:mpi_wrap.py
示例17: _establish_tls_with_client
def _establish_tls_with_client(self):
self.log("Establish TLS with client", "debug")
cert, key, chain_file = self._find_cert()
try:
self.client_conn.convert_to_ssl(
cert, key,
method=self.config.openssl_method_client,
options=self.config.openssl_options_client,
cipher_list=self.config.ciphers_client,
dhparams=self.config.certstore.dhparams,
chain_file=chain_file,
alpn_select_callback=self.__alpn_select_callback,
)
# Some TLS clients will not fail the handshake,
# but will immediately throw an "unexpected eof" error on the first read.
# The reason for this might be difficult to find, so we try to peek here to see if it
# raises ann error.
self.client_conn.rfile.peek(1)
except TlsException as e:
six.reraise(
ClientHandshakeException,
ClientHandshakeException(
"Cannot establish TLS with client (sni: {sni}): {e}".format(
sni=self.client_sni, e=repr(e)
),
self.client_sni or repr(self.server_conn.address)
),
sys.exc_info()[2]
)
开发者ID:KiteGh0st,项目名称:opparis,代码行数:30,代码来源:tls.py
示例18: input_elements
def input_elements(self, instruction_id, expected_targets):
"""
Generator to retrieve elements for an instruction_id
input_elements should be called only once for an instruction_id
Args:
instruction_id(str): instruction_id for which data is read
expected_targets(collection): expected targets
"""
received = self._receiving_queue(instruction_id)
done_targets = []
try:
while len(done_targets) < len(expected_targets):
try:
data = received.get(timeout=1)
except queue.Empty:
if self._exc_info:
t, v, tb = self._exc_info
six.reraise(t, v, tb)
else:
if not data.data and data.target in expected_targets:
done_targets.append(data.target)
else:
assert data.target not in done_targets
yield data
finally:
# Instruction_ids are not reusable so Clean queue once we are done with
# an instruction_id
self._clean_receiving_queue(instruction_id)
开发者ID:JavierRoger,项目名称:beam,代码行数:29,代码来源:data_plane.py
示例19: _run_request
def _run_request(self, url, method, headers, body):
"""Run the http request and decode output.
The call to make the request will catch a WSGIAppError from
wsgi_intercept so that the real traceback from a catastrophic
error in the intercepted app can be examined.
"""
try:
response, content = self.http.request(
url,
method=method,
headers=headers,
body=body
)
except wsgi_intercept.WSGIAppError as exc:
# Extract and re-raise the wrapped exception.
six.reraise(exc.exception_type, exc.exception_value,
exc.traceback)
# Set headers and location attributes for follow on requests
self.response = response
if 'location' in response:
self.location = response['location']
# Decode and store response
decoded_output = utils.decode_content(response, content)
if (decoded_output and
'application/json' in response.get('content-type', '')):
self.json_data = json.loads(decoded_output)
self.output = decoded_output
开发者ID:ravichandrasadineni,项目名称:gabbi,代码行数:31,代码来源:case.py
示例20: _save
def _save(self, name, content):
# Taken from django.core.files.storage.FileSystemStorage._save
# Need to allow overwrite
full_path = self.path(name)
directory = os.path.dirname(full_path)
if not os.path.exists(directory):
try:
if self.directory_permissions_mode is not None:
# os.makedirs applies the global umask, so we reset it,
# for consistency with file_permissions_mode behavior.
old_umask = os.umask(0)
try:
os.makedirs(directory, self.directory_permissions_mode)
finally:
os.umask(old_umask)
else:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
six.reraise(*sys.exc_info())
if not os.path.isdir(directory):
raise IOError("%s exists and is not a directory." % directory)
with open(full_path, 'w') as f:
for chunk in content.chunks():
f.write(chunk)
if self.file_permissions_mode is not None:
os.chmod(full_path, self.file_permissions_mode)
return name
开发者ID:rlugojr,项目名称:portia,代码行数:32,代码来源:backends.py
注:本文中的six.reraise函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论