我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用six.reraise()。
def raise_error(self, exc, identity=None): if isinstance(exc, ApiUnauthorized): six.reraise( InvalidIdentity, InvalidIdentity(self.message_from_error(exc), identity=identity), sys.exc_info()[2] ) elif isinstance(exc, ApiError): six.reraise( PluginError, PluginError(self.message_from_error(exc)), sys.exc_info()[2] ) elif isinstance(exc, PluginError): raise else: self.logger.exception(six.text_type(exc)) six.reraise( PluginError, PluginError(self.message_from_error(exc)), sys.exc_info()[2] )
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: 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' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
def decrypt(self): """Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption. """ if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params) return plaintext except Exception as e: exc_info = sys.exc_info() six.reraise( ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)), None, exc_info[2] )
def render(self): """Renders the tab to HTML using the :meth:`~horizon.tabs.Tab.get_context_data` method and the :meth:`~horizon.tabs.Tab.get_template_name` method. If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load`` is not ``True``, or either :meth:`~horizon.tabs.Tab.allowed` or :meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will return an empty string. """ if not self.load: return '' try: context = self.data except exceptions.Http302: raise except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback) return render_to_string(self.get_template_name(self.request), context)
def get_rows(self): """Return the row data for this table broken out by columns.""" rows = [] try: for datum in self.filtered_data: row = self._meta.row_class(self, datum) if self.get_object_id(datum) == self.current_item_id: self.selected = True row.classes.append('current_selected') rows.append(row) except Exception: # Exceptions can be swallowed at the template level here, # re-raising as a TemplateSyntaxError makes them visible. LOG.exception("Error while rendering table rows.") exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) return rows
def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in 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() LOG.exception('Exception in string format operation') for name, value in six.iteritems(kwargs): LOG.error("%s: %s" % (name, value)) six.reraise(*exc_info) self.message = message super(WeiboError, self).__init__(message)
def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in 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() LOG.exception('Exception in string format operation') for name, value in six.iteritems(kwargs): LOG.error("%s: %s" % (name, value)) six.reraise(*exc_info) self.message = message super(LoginserverError, self).__init__(message)
def docker_client(): client_kwargs = dict() if not CONF.docker.api_insecure: client_kwargs['ca_cert'] = CONF.docker.ca_file client_kwargs['client_key'] = CONF.docker.key_file client_kwargs['client_cert'] = CONF.docker.cert_file try: yield DockerHTTPClient( CONF.docker.api_url, CONF.docker.docker_remote_api_version, CONF.docker.default_timeout, **client_kwargs ) except errors.APIError as e: desired_exc = exception.DockerError(error_msg=six.text_type(e)) six.reraise(type(desired_exc), desired_exc, sys.exc_info()[2])
def __call__(self, ex): """Re-raise any exception value not being filtered out. If the exception was the last to be raised, it will be re-raised with its original traceback. """ exc_type, exc_val, traceback = sys.exc_info() try: if not self._should_ignore_ex(ex): if exc_val is ex: six.reraise(exc_type, exc_val, traceback) else: raise ex finally: del exc_type, exc_val, traceback
def raise_for_status(self, allow_redirects=True): """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.""" if self.status_code == 304: return elif self.error: if self.traceback: six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback()) http_error = HTTPError(self.error) elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects: http_error = HTTPError('%s Redirection' % (self.status_code)) elif (self.status_code >= 400) and (self.status_code < 500): http_error = HTTPError('%s Client Error' % (self.status_code)) elif (self.status_code >= 500) and (self.status_code < 600): http_error = HTTPError('%s Server Error' % (self.status_code)) else: return http_error.response = self raise http_error
def setUpClass(cls): # It should never be overridden by descendants if hasattr(super(BaseTestCase, cls), 'setUpClass'): super(BaseTestCase, cls).setUpClass() cls.setUpClassCalled = True # Stack of (name, callable) to be invoked in reverse order at teardown cls.teardowns = [] try: # Shortcuts to clients cls.setup_clients() cls.resource_setup() except Exception: etype, value, trace = sys.exc_info() LOG.info("%s raised in %s.setUpClass. Invoking tearDownClass." % ( etype, cls.__name__)) cls.tearDownClass() try: six.reraise(etype, value, trace) finally: del trace # to avoid circular refs
def run_callbacks(self): for f in self.fields: keys = self.frb.keys() for name, (args, kwargs) in self._callbacks: cbw = CallbackWrapper(self, self.plots[f], self.frb, f, self._font_properties, self._font_color) CallbackMaker = callback_registry[name] callback = CallbackMaker(*args[1:], **kwargs) try: callback(cbw) except YTDataTypeUnsupported as e: six.reraise(YTDataTypeUnsupported, e) except Exception as e: six.reraise(YTPlotCallbackError, YTPlotCallbackError(callback._type_name, e), sys.exc_info()[2]) for key in self.frb.keys(): if key not in keys: del self.frb[key]
def byte_END_FINALLY(self): v = self.pop() if isinstance(v, str): why = v if why in ('return', 'continue'): self.return_value = self.pop() if why == 'silenced': # PY3 block = self.pop_block() assert block.type == 'except-handler' self.unwind_block(block) why = None elif v is None: why = None elif issubclass(v, BaseException): exctype = v val = self.pop() tb = self.pop() self.last_exception = (exctype, val, tb) why = 'reraise' else: # pragma: no cover raise VirtualMachineError("Confused END_FINALLY") return why
def from_except(cls, name, tb, exception, error_html_getter=None, error_html_getter_params={}, **data): try: from celery.exceptions import Retry except ImportError: pass else: if isinstance(exception, Retry): six.reraise(Retry, exception, tb) tb_stacks = traceback.extract_tb(tb) stack_list = [ (cls._normalize_file_python(src_path), lineno, func_name, src_code) for src_path, lineno, func_name, src_code in tb_stacks ] error_html_getter = error_html_getter or (lambda exc_type, exc_value, tb, **kwargs: Reporter(exc_type, exc_value, tb).get_traceback_html()) data[cls.name_property] = name res = cls( stack_hash=cls._get_stack_hash(stack_list), error_type=cls._get_except_cls_name(type(exception)), error_html=error_html_getter(exc_type=type(exception), exc_value=exception, tb=tb, **error_html_getter_params), **data ) res.stack_list = stack_list res.error_args = [repr(arg) for arg in exception.args] return res
def _scan(self, fs, dir_path, namespaces): """Get an iterator of `Info` objects for a directory path. Arguments: fs (FS): A filesystem instance. dir_path (str): A path to a directory on the filesystem. namespaces (list): A list of additional namespaces to include in the `Info` objects. Returns: ~collections.Iterator: iterator of `Info` objects for resources within the given path. """ try: for info in fs.scandir(dir_path, namespaces=namespaces): yield info except FSError as error: if not self.on_error(dir_path, error): six.reraise(type(error), error)
def __exit__(self, exc_type, exc_value, traceback): ssh_errors = ( self.DIR_ERRORS if self._directory else self.FILE_ERRORS ) if exc_type and isinstance(exc_value, EnvironmentError): _errno = exc_value.errno fserror = ssh_errors.get(_errno, errors.OperationFailed) if _errno == errno.EACCES and sys.platform == "win32": if getattr(exc_value, 'args', None) == 32: # pragma: no cover fserror = errors.ResourceLocked six.reraise( fserror, fserror( self._path, exc=exc_value ), traceback ) # Stops linter complaining about invalid class name
def _put_s3_object(key, body): ''' Put an object in S3. ''' s3_client = boto3.client('s3') try: response = s3_client.put_object( Body=body, Bucket=TS_AWS_S3_BUCKET, Key=key ) except ClientError as e: exc_info = sys.exc_info() if sys.version_info >= (3,0,0): raise S3ClientError(e).with_traceback(exc_info[2]) else: six.reraise(S3ClientError, S3ClientError(e), exc_info[2]) except RequestException as e: exc_info = sys.exc_info() if sys.version_info >= (3,0,0): raise S3ClientError('Failure to communicate with S3').with_traceback(exc_info[2]) else: six.reraise(S3ClientError, S3ClientError('Failure to communicate with S3'), exc_info[2]) return response
def is_available(): ''' Check ability to access S3 bucket. ''' s3_client = boto3.client('s3') try: kwargs = {'Bucket': TS_AWS_S3_BUCKET} if TS_AWS_S3_PREFIX: kwargs['Prefix'] = TS_AWS_S3_PREFIX s3_client.list_objects(**kwargs) except ClientError as e: exc_info = sys.exc_info() if sys.version_info >= (3,0,0): raise S3ClientError(e).with_traceback(exc_info[2]) else: six.reraise(S3ClientError, S3ClientError(e), exc_info[2]) except RequestException as e: exc_info = sys.exc_info() if sys.version_info >= (3,0,0): raise S3ClientError('Failure to communicate with S3').with_traceback(exc_info[2]) else: six.reraise(S3ClientError, S3ClientError('Failure to communicate with S3'), exc_info[2]) return True
def close(self): """Closes event log reader if open. If the i/o thread is running, this method blocks until it has been shut down. Further reads are not permitted after this method is called. Raises: Exception: To propagate any exceptions that may have been thrown by the close operation in the other thread. If an exception is thrown, then all subsequent calls to this method will rethrow that same exception. """ with self._lock: if not self._is_closed: self._is_closed = True if not self._thread.is_alive(): self._reader = None return self._wake_up_producer.notify() while self._reader is not None: self._wake_up_consumers.wait() if self._close_exception is not None: six.reraise(*self._close_exception)
def close_all(resources): """Safely closes multiple resources. The close method on all resources is guaranteed to be called. If multiple close methods throw exceptions, then the first will be raised and the rest will be logged. Args: resources: An iterable of object instances whose classes implement the close method. Raises: Exception: To rethrow the last exception raised by a close method. """ exc_info = None for resource in resources: try: resource.close() except Exception as e: # pylint: disable=broad-except if exc_info is not None: tf.logging.error('Suppressing close(%s) failure: %s', resource, e, exc_info=exc_info) exc_info = sys.exc_info() if exc_info is not None: six.reraise(*exc_info)
def run_once(function, state={}, errors={}): """A memoization decorator, whose purpose is to cache calls.""" @six.wraps(function) def _wrapper(*args, **kwargs): if function in errors: # Deliberate use of LBYL. six.reraise(*errors[function]) try: return state[function] except KeyError: try: state[function] = result = function(*args, **kwargs) return result except Exception: errors[function] = sys.exc_info() raise return _wrapper
def less_shitty_error_messages(func): """ Wraps functions where the first param is a SQL statement and enforces any exceptions thrown will also contain the statement in the message. """ @wraps(func) def inner(self, sql, *args, **kwargs): try: return func(self, sql, *args, **kwargs) except Exception as e: exc_info = sys.exc_info() msg = '{}\nSQL: {}'.format( e.message, sql, ) six.reraise(exc_info[0], exc_info[0](msg), exc_info[2]) return inner
def get_multi(self, id_list): # shortcut for just one id since this is a common # case for us from EventManager.bind_nodes if len(id_list) == 1: id = id_list[0] return {id: self.get(id)} rv = self.conn.multiget(self.bucket, id_list, r=1) results = {} for key, value in rv.iteritems(): if isinstance(value, Exception): six.reraise(type(value), value) if value.status != 200: results[key] = None else: results[key] = json.loads(value.data) return results
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
def stop(self): """Wait for the worker threads to process all items in queue. This method blocks until there is no more work left. It is essential to call this method. If you do any work in between ``start`` and ``stop``, make sure the ``stop`` method will always be called, otherwise the program will never exit. """ for i in self.threads: i.running = False for i in self.threads: i.join() if self.exceptions: exc_info = self.exceptions[0] six.reraise(exc_info[0], exc_info[1], exc_info[2])
def create_security_group(self, context, name, description): neutron = neutronapi.get_client(context) body = self._make_neutron_security_group_dict(name, description) try: security_group = neutron.create_security_group( body).get('security_group') except n_exc.BadRequest as e: raise exception.Invalid(six.text_type(e)) except n_exc.NeutronClientException as e: exc_info = sys.exc_info() LOG.exception(_LE("Neutron Error creating security group %s"), name) if e.status_code == 401: # TODO(arosen) Cannot raise generic response from neutron here # as this error code could be related to bad input or over # quota raise exc.HTTPBadRequest() elif e.status_code == 409: self.raise_over_quota(six.text_type(e)) six.reraise(*exc_info) return self._convert_to_nova_security_group_format(security_group)
def update_security_group(self, context, security_group, name, description): neutron = neutronapi.get_client(context) body = self._make_neutron_security_group_dict(name, description) try: security_group = neutron.update_security_group( security_group['id'], body).get('security_group') except n_exc.NeutronClientException as e: exc_info = sys.exc_info() LOG.exception(_LE("Neutron Error updating security group %s"), name) if e.status_code == 401: # TODO(arosen) Cannot raise generic response from neutron here # as this error code could be related to bad input or over # quota raise exc.HTTPBadRequest() six.reraise(*exc_info) return self._convert_to_nova_security_group_format(security_group)
def translate_cinder_exception(method): """Transforms a cinder exception but keeps its traceback intact.""" @functools.wraps(method) def wrapper(self, ctx, *args, **kwargs): try: res = method(self, ctx, *args, **kwargs) except (cinder_exception.ConnectionError, keystone_exception.ConnectionError): exc_type, exc_value, exc_trace = sys.exc_info() exc_value = exception.CinderConnectionFailed( reason=six.text_type(exc_value)) six.reraise(exc_value, None, exc_trace) except (keystone_exception.BadRequest, cinder_exception.BadRequest): exc_type, exc_value, exc_trace = sys.exc_info() exc_value = exception.InvalidInput( reason=six.text_type(exc_value)) six.reraise(exc_value, None, exc_trace) except (keystone_exception.Forbidden, cinder_exception.Forbidden): exc_type, exc_value, exc_trace = sys.exc_info() exc_value = exception.Forbidden(message=six.text_type(exc_value)) six.reraise(exc_value, None, exc_trace) return res return wrapper
def convert_exceptions(function, exception_map): expected_exceptions = tuple(exception_map.keys()) @functools.wraps(function) def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except expected_exceptions as ex: raised_exception = exception_map.get(type(ex)) if not raised_exception: # exception might be a subclass of an expected exception. for expected in expected_exceptions: if isinstance(ex, expected): raised_exception = exception_map[expected] break exc_info = sys.exc_info() # NOTE(claudiub): Python 3 raises the exception object given as # the second argument in six.reraise. # The original message will be maintained by passing the original # exception. exc = raised_exception(six.text_type(exc_info[1])) six.reraise(raised_exception, exc, exc_info[2]) return wrapper
def _handle_create_exception(*exc_info): """The `CREATE_EXCEPTIONS` dict containing the relationships between the nova exceptions and the webob exception classes to be raised is defined at the top of this file. """ error = exc_info[1] err_cls = error.__class__ cls_to_raise = CREATE_EXCEPTIONS.get(err_cls) if cls_to_raise is None: # The error is a subclass of one of the dict keys to_raise = [val for key, val in CREATE_EXCEPTIONS.items() if isinstance(error, key)] if len(to_raise) > 1: cls_to_raise = Controller._resolve_exception(to_raise) elif not to_raise: # Not any of the expected exceptions, so re-raise six.reraise(*exc_info) else: cls_to_raise = to_raise[0] for key, val in CREATE_EXCEPTIONS_MSGS.items(): if isinstance(error, key): raise cls_to_raise(explanation=CREATE_EXCEPTIONS_MSGS[key]) raise cls_to_raise(explanation=error.format_message())
def load(self): """Load controlled schema version info from DB""" tname = self.repository.version_table try: if not hasattr(self, 'table') or self.table is None: self.table = Table(tname, self.meta, autoload=True) result = self.engine.execute(self.table.select( self.table.c.repository_id == str(self.repository.id))) data = list(result)[0] except: cls, exc, tb = sys.exc_info() six.reraise(exceptions.DatabaseNotControlledError, exceptions.DatabaseNotControlledError(str(exc)), tb) self.version = data['version'] return data
def get(self, wrap_exception=False): """ Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. """ if self.has_exception: if wrap_exception: raise RetryError(self) else: six.reraise(self.value[0], self.value[1], self.value[2]) else: return self.value
def _raise(exc): if six.PY2 and isinstance(exc, tuple): (exc_type, value, traceback) = exc six.reraise(exc_type, value, traceback) else: raise exc
def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in self.kwargs: try: self.kwargs['code'] = self.code except AttributeError: pass for k, v in self.kwargs.items(): if isinstance(v, Exception): self.kwargs[k] = six.text_type(v) if self._should_format(message): try: message = self.message % 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 kwargs.items(): LOG.error(_LE("%(name)s: %(value)s"), {'name': name, 'value': value}) if CONF.fatal_exception_format_errors: six.reraise(*exc_info) # at least get the core message out if something happened message = self.message elif isinstance(message, Exception): message = six.text_type(message) # NOTE(luisg): We put the actual message in 'msg' so that we can access # it, because if we try to access the message via 'message' it will be # overshadowed by the class' message attribute self.msg = message super(VDIBrokerException, self).__init__(message)
def get_connection(alias=DEFAULT_CONNECTION_NAME, db=None): global _connections global _default_dbs if alias not in _connections: conn_settings = _connection_settings[alias].copy() db = conn_settings.pop('name', None) connection_class = MotorClient if 'replicaSet' in conn_settings: connection_class = MotorReplicaSetClient conn_settings['hosts_or_uri'] = conn_settings.pop('host', None) # Discard port since it can't be used on MongoReplicaSetClient conn_settings.pop('port', None) # Discard replicaSet if not base string if not isinstance(conn_settings['replicaSet'], six.string_types): conn_settings.pop('replicaSet', None) try: _connections[alias] = connection_class(**conn_settings) except Exception: exc_info = sys.exc_info() err = ConnectionError("Cannot connect to database %s :\n%s" % (alias, exc_info[1])) raise six.reraise(ConnectionError, err, exc_info[2]) try: if not _connections[alias].connected: _connections[alias].open_sync() except Exception: exc_info = sys.exc_info() err = ConnectionError("Cannot connect to database %s :\n%s" % (alias, exc_info[1])) raise six.reraise(ConnectionError, err, exc_info[2]) database = None if db is None: database = getattr(_connections[alias], _default_dbs[alias]) else: database = getattr(_connections[alias], db) return Database(_connections[alias], database)
def get_rows(self): """Return the row data for this table broken out by columns. The row objects get an additional ``form`` parameter, with the formset form corresponding to that row. """ try: rows = [] if self.formset_class is None: formset = [] else: formset = self.get_formset() formset.is_valid() for datum, form in six.moves.zip_longest(self.filtered_data, formset): row = self._meta.row_class(self, datum, form) if self.get_object_id(datum) == self.current_item_id: self.selected = True row.classes.append('current_selected') rows.append(row) except Exception: # Exceptions can be swallowed at the template level here, # re-raising as a TemplateSyntaxError makes them visible. LOG.exception("Error while rendering table rows.") exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) return rows
def value(self): """Returns a formatted version of the data for final output. This takes into consideration the :attr:`~horizon.tables.Column.link`` and :attr:`~horizon.tables.Column.empty_value` attributes. """ try: data = self.column.get_data(self.datum) if data is None: if callable(self.column.empty_value): data = self.column.empty_value(self.datum) else: data = self.column.empty_value except Exception: data = None exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) if self.url and not self.column.auto == "form_field": link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in self.column.link_attrs.items()]) # Escape the data inside while allowing our HTML to render data = mark_safe('<a href="%s" %s>%s</a>' % ( (escape(self.url), link_attrs, escape(six.text_type(data))))) return data
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) # re-raise possibly-amended exception with original traceback: six.reraise(type(exc), exc, sys.exc_info()[2])
def _reraise_translated_image_exception(image_id): """Transform the exception for the image but keep its traceback intact.""" # pylint: disable=unused-variable _exc_type, exc_value, exc_trace = sys.exc_info() new_exc = _translate_image_exception(image_id, exc_value) six.reraise(type(new_exc), new_exc, exc_trace)
def _reraise_translated_exception(): """Transform the exception but keep its traceback intact.""" # pylint: disable=unused-variable _exc_type, exc_value, exc_trace = sys.exc_info() new_exc = _translate_plain_exception(exc_value) six.reraise(type(new_exc), new_exc, exc_trace)
def __get__(self, instance, owner): # Tell the ClientManager to login to keystone if self._handle is None: try: self._handle = self.factory(instance) except AttributeError as err: # Make sure the failure propagates. Otherwise, the plugin just # quietly isn't there. new_err = exceptions.PluginAttributeError(err) six.reraise(new_err.__class__, new_err, sys.exc_info()[2]) return self._handle
def __init__(self, reraise=True, logger=None): self.reraise = reraise if logger is None: logger = logging.getLogger() self.logger = logger self.type_, self.value, self.tb = (None, None, None)
def force_reraise(self): if self.type_ is None and self.value is None: raise RuntimeError("There is no (currently) captured exception" " to force the reraising of") six.reraise(self.type_, self.value, self.tb)
def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: if self.reraise: self.logger.error(_LE('Original exception being dropped: %s'), traceback.format_exception(self.type_, self.value, self.tb)) return False if self.reraise: self.force_reraise()
def apply_rules(*rules): def decorator(func): @wraps(func) def api_rule_check_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except RQInvalidArgument: raise except Exception: exc_info = sys.exc_info() t, v, tb = exc_info try: call_args = inspect.getcallargs(unwrapper(func), *args, **kwargs) except TypeError as e: six.reraise(RQTypeError, RQTypeError(*e.args), tb) return try: for r in rules: r.verify(func.__name__, call_args[r.arg_name]) except RQInvalidArgument as e: six.reraise(RQInvalidArgument, e, tb) return raise api_rule_check_wrapper._rq_exception_checked = True return api_rule_check_wrapper return decorator
def load(taskName,ignoreEntities=[]): """ Download and load the corresponding corpus from the BioNLP Shared Task :param taskName: The name of the shared task to download (e.g. 'BioNLP-ST-2016_BB-event_train'). Use kindred.bionlpst.listTasks() to get a list of valid options :param ignoreEntities: A list of any entities that should be ignored during loading :type taskName: str :type ignoreEntities: list of str :return: The loaded corpus :rtype: kindred.Corpus """ global taskOptions tempDir = tempfile.mkdtemp() assert taskName in taskOptions.keys(), "%s not a valid option in %s" % (taskName, taskOptions.keys()) url,expectedFile,expectedSHA256 = taskOptions[taskName] filesToDownload = [(url,expectedFile,expectedSHA256)] expectedDir = expectedFile.replace('.zip','') try: kindred.utils._downloadFiles(filesToDownload,tempDir) except: exc_info = sys.exc_info() shutil.rmtree(tempDir) six.reraise(*exc_info) mainDir = kindred.utils._findDir(expectedDir,tempDir) corpus = kindred.loadDir(dataFormat='standoff',directory=mainDir,ignoreEntities=ignoreEntities) shutil.rmtree(tempDir) return corpus
def resume(self): "restore and re-raise any exception" if '_saved' not in vars(self): return type, exc = map(pickle.loads, self._saved) six.reraise(type, exc, self._tb)