Python six.raise_from() Examples

The following are 30 code examples of six.raise_from(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six , or try the search function .
Example #1
Source File: killmail.py    From evesrp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #2
Source File: isoparser.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: sql_schedule_storage.py    From dagster with Apache License 2.0 6 votes vote down vote up
def create_schedule_tick(self, schedule_tick_data):
        check.inst_param(schedule_tick_data, 'schedule_tick_data', ScheduleTickData)

        with self.connect() as conn:
            try:
                tick_insert = ScheduleTickTable.insert().values(  # pylint: disable=no-value-for-parameter
                    schedule_origin_id=schedule_tick_data.schedule_origin_id,
                    status=schedule_tick_data.status.value,
                    timestamp=utc_datetime_from_timestamp(schedule_tick_data.timestamp),
                    tick_body=serialize_dagster_namedtuple(schedule_tick_data),
                )
                result = conn.execute(tick_insert)
                tick_id = result.inserted_primary_key[0]
                return ScheduleTick(tick_id, schedule_tick_data)
            except db.exc.IntegrityError as exc:
                six.raise_from(
                    DagsterInvariantViolationError(
                        'Unable to insert ScheduleTick for schedule {schedule_name} in storage'.format(
                            schedule_name=schedule_tick_data.schedule_name,
                        )
                    ),
                    exc,
                ) 
Example #4
Source File: stream.py    From gnsq with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #5
Source File: stream.py    From gnsq with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: base.py    From syntribos with Apache License 2.0 6 votes vote down vote up
def tearDownClass(cls):
        super(BaseTestCase, cls).tearDownClass()
        if not cls.failures:
            if "EXCEPTION_RAISED" in cls.test_signals:
                sig = cls.test_signals.find(
                    tags="EXCEPTION_RAISED")[0]
                exc_name = type(sig.data["exception"]).__name__
                if ("CONNECTION_FAIL" in sig.tags):
                    six.raise_from(FatalHTTPError(
                        "The remote target has forcibly closed the connection "
                        "with Syntribos and resulted in exception '{}'. This "
                        "could potentially mean that a fatal error was "
                        "encountered within the target application or server"
                        " itself.".format(exc_name)), sig.data["exception"])
                else:
                    raise sig.data["exception"] 
Example #7
Source File: registry.py    From datapackage-py with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: registry.py    From datapackage-py with MIT License 6 votes vote down vote up
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 
Example #9
Source File: sql.py    From dagster with Apache License 2.0 6 votes vote down vote up
def handle_schema_errors(conn, alembic_config, msg=None):
    try:
        yield
    except (db.exc.OperationalError, db.exc.ProgrammingError, db.exc.StatementError) as exc:
        db_revision, head_revision = (None, None)

        try:
            with quieten():
                db_revision, head_revision = check_alembic_revision(alembic_config, conn)
        # If exceptions were raised during the revision check, we want to swallow them and
        # allow the original exception to fall through
        except Exception:  # pylint: disable=broad-except
            pass

        if db_revision != head_revision:
            six.raise_from(
                DagsterInstanceMigrationRequired(
                    msg=msg, db_revision=db_revision, head_revision=head_revision
                ),
                exc,
            )

        raise 
Example #10
Source File: mock.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: isoparser.py    From recruit with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: checks.py    From engarde with MIT License 6 votes vote down vote up
def is_same_as(df, df_to_compare, **kwargs):
    """
    Assert that two pandas dataframes are the equal

    Parameters
    ==========
    df : pandas DataFrame
    df_to_compare : pandas DataFrame
    **kwargs : dict
        keyword arguments passed through to panda's ``assert_frame_equal``

    Returns
    =======
    df : DataFrame

    """
    try:
        tm.assert_frame_equal(df, df_to_compare, **kwargs)
    except AssertionError as exc:
        six.raise_from(AssertionError("DataFrames are not equal"), exc)
    return df 
Example #13
Source File: sql_schedule_storage.py    From dagster with Apache License 2.0 6 votes vote down vote up
def add_schedule_state(self, schedule):
        check.inst_param(schedule, 'schedule', ScheduleState)
        with self.connect() as conn:
            try:
                schedule_insert = ScheduleTable.insert().values(  # pylint: disable=no-value-for-parameter
                    schedule_origin_id=schedule.schedule_origin_id,
                    repository_origin_id=schedule.repository_origin_id,
                    status=schedule.status.value,
                    schedule_body=serialize_dagster_namedtuple(schedule),
                )
                conn.execute(schedule_insert)
            except db.exc.IntegrityError as exc:
                six.raise_from(
                    DagsterInvariantViolationError(
                        'ScheduleState {id} is already present '
                        'in storage'.format(id=schedule.schedule_origin_id,)
                    ),
                    exc,
                )

        return schedule 
Example #14
Source File: isoparser.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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 
Example #15
Source File: inference.py    From dagster with Apache License 2.0 6 votes vote down vote up
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,
        ) 
Example #16
Source File: middleware.py    From cloudbridge with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: isoparser.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 
Example #18
Source File: isoparser.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
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 
Example #19
Source File: _parser.py    From pipenv with MIT License 6 votes vote down vote up
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. 
Example #20
Source File: isoparser.py    From pipenv with MIT License 6 votes vote down vote up
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 
Example #21
Source File: isoparser.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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 
Example #22
Source File: utils.py    From gin-config with Apache License 2.0 6 votes vote down vote up
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]) 
Example #23
Source File: credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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) 
Example #24
Source File: retrier.py    From riprova with MIT License 6 votes vote down vote up
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 
Example #25
Source File: isoparser.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
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 
Example #26
Source File: _mtls_helper.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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 
Example #27
Source File: parser.py    From linter-pylama with MIT License 6 votes vote down vote up
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 
Example #28
Source File: _client.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def jwt_grant(request, token_uri, assertion):
    """Implements the JWT Profile for OAuth 2.0 Authorization Grants.

    For more details, see `rfc7523 section 4`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        assertion (str): The OAuth 2.0 assertion.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
            expiration, and additional data returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
    """
    body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}

    response_data = _token_endpoint_request(request, token_uri, body)

    try:
        access_token = response_data["access_token"]
    except KeyError as caught_exc:
        new_exc = exceptions.RefreshError("No access token in response.", response_data)
        six.raise_from(new_exc, caught_exc)

    expiry = _parse_expiry(response_data)

    return access_token, expiry, response_data 
Example #29
Source File: _parser.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 5 votes vote down vote up
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 
Example #30
Source File: retrier.py    From riprova with MIT License 5 votes vote down vote up
def _get_delay(self):
        # Get delay before next retry
        delay = self.backoff.next()

        # If backoff is done, raise an exception
        if delay == Backoff.STOP:
            return raise_from(MaxRetriesExceeded('max retries exceeded'),
                              self.error)

        return delay