當前位置: 首頁>>代碼示例>>Python>>正文


Python six.raise_from方法代碼示例

本文整理匯總了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 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:19,代碼來源:parser.py

示例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 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:20,代碼來源:isoparser.py

示例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 
開發者ID:frictionlessdata,項目名稱:datapackage-py,代碼行數:25,代碼來源:registry.py

示例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) 
開發者ID:frictionlessdata,項目名稱:datapackage-py,代碼行數:18,代碼來源:registry.py

示例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 
開發者ID:wtolson,項目名稱:gnsq,代碼行數:23,代碼來源:stream.py

示例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) 
開發者ID:wtolson,項目名稱:gnsq,代碼行數:23,代碼來源:stream.py

示例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) 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:23,代碼來源:mock.py

示例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) 
開發者ID:CloudVE,項目名稱:cloudbridge,代碼行數:20,代碼來源:middleware.py

示例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. 
開發者ID:pypa,項目名稱:pipenv,代碼行數:19,代碼來源:_parser.py

示例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) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:22,代碼來源:credentials.py

示例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 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:22,代碼來源:_mtls_helper.py

示例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 
開發者ID:paxswill,項目名稱:evesrp,代碼行數:22,代碼來源:killmail.py

示例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 
開發者ID:h2non,項目名稱:riprova,代碼行數:24,代碼來源:retrier.py

示例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]) 
開發者ID:google,項目名稱:gin-config,代碼行數:26,代碼來源:utils.py

示例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,
        ) 
開發者ID:dagster-io,項目名稱:dagster,代碼行數:23,代碼來源:inference.py


注:本文中的six.raise_from方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。