• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python six.raise_from函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.raise_from函数的典型用法代码示例。如果您正苦于以下问题:Python raise_from函数的具体用法?Python raise_from怎么用?Python raise_from使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了raise_from函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:sbuss,项目名称:py-multiaddr,代码行数:7,代码来源:uint16be.py


示例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))
开发者ID:00WhengWheng,项目名称:shuup,代码行数:27,代码来源:package_forms.py


示例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
开发者ID:trown,项目名称:tripleo-common,代码行数:32,代码来源:plan.py


示例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))
开发者ID:Zyell,项目名称:bokeh,代码行数:34,代码来源:export.py


示例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)
开发者ID:RodrigoMG07,项目名称:ChallengeDrive,代码行数:32,代码来源:_oauth2client.py


示例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
开发者ID:doomcat55,项目名称:malcat,代码行数:7,代码来源:api.py


示例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
开发者ID:larsyencken,项目名称:cjktools,代码行数:29,代码来源:tatoeba.py


示例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')
开发者ID:TonyFlury,项目名称:manifest-checker,代码行数:30,代码来源:processor.py


示例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')
开发者ID:TonyFlury,项目名称:manifest-checker,代码行数:35,代码来源:processor.py


示例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()
开发者ID:NuttasitBoonwat,项目名称:sentry,代码行数:25,代码来源:lock.py


示例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)
开发者ID:TonyFlury,项目名称:manifest-checker,代码行数:30,代码来源:processor.py


示例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]
开发者ID:triplekill,项目名称:touchdown,代码行数:7,代码来源:action.py


示例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
开发者ID:dahlbaek,项目名称:datapackage-py,代码行数:28,代码来源:profile.py


示例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'))
开发者ID:JianyuWang,项目名称:oslo.utils,代码行数:35,代码来源:excutils.py


示例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)
开发者ID:VertNet,项目名称:post-harvest-processor,代码行数:31,代码来源:requests.py


示例16: _config_operator_list_modifiers

    def _config_operator_list_modifiers(self, attr_name, values, line, line_no,
                                        op,
                                        section):
        """Execute + <list>, -<list> or =<list> line in config file

            Used in the extension and directories section
            :param attr_name: The instance attribute to change
            :param values: The values from the config file
            :param line: The full line from the config file
            :param line_no: the line number of this line
            :param op: The actual operation (one of +,- or =)
            :param section: The section of the config file
        """
        if op == '=':
            setattr(self, attr_name, values)
            return

        if not values:
            six.raise_from(ConfigError(
                'Invalid value in [{section}] section :'
                ' \'{line}\' on line {line_no}'.format(
                    section=section, line=line, line_no=line_no)), None)

        if op == '+':
            setattr(self, attr_name, getattr(self, attr_name) | values)
        elif op == '-':
            setattr(self, attr_name, getattr(self, attr_name) - values)
        else:
            six.raise_from(ConfigError(
                'Invalid operator in [{section}] section :'
                ' \'{line}\' on line {line_no}'.format(
                    section=section, line=line, line_no=line_no)), None)
开发者ID:TonyFlury,项目名称:manifest-checker,代码行数:32,代码来源:processor.py


示例17: _get_profile

    def _get_profile(self, profile_id):
        '''dict: Return the profile with the received ID as a dict (None if it
        doesn't exist).'''
        profile_metadata = self._registry.get(profile_id)
        if not profile_metadata:
            return

        path = self._get_absolute_path(profile_metadata.get('schema_path'))
        url = profile_metadata.get('schema')
        if path:
            try:
                return self._load_json_file(path)
            except IOError as local_exc:
                if not url:
                    raise local_exc

                try:
                    return self._load_json_url(url)
                except IOError:
                    msg = (
                        'Error loading profile locally at "{path}" '
                        'and remotely at "{url}".'
                    ).format(path=path, url=url)
                    six.raise_from(IOError(msg), local_exc)
        elif url:
            return self._load_json_url(url)
开发者ID:scls19fr,项目名称:datapackage-py,代码行数:26,代码来源:registry.py


示例18: reset

 def reset(self):
     """! @brief Reset the target"""
     try:
         self._invalidate_cached_registers()
         self._link.reset()
     except DAPAccess.Error as exc:
         six.raise_from(self._convert_exception(exc), exc)
开发者ID:flit,项目名称:pyOCD,代码行数:7,代码来源:cmsis_dap_probe.py


示例19: details

    def details(self, sent_id):
        """
        Retrieve additional details about a given sentence.

        :param sent_id:
            A valid sentence ID.

        :raises MissingDataError:
            Raised if detailed sentence information was not loaded into the
            reader.

        :raises InvalidIDError:
            Raised if an invalid sentence ID is passed.

        :returns:
            Returns a tuple of the form:

            ``(username, date_added, date_modified)``

            All three are strings. 
        """
        if self._detailed_info_dict is None:
            raise MissingDataError('Detailed information not loaded.')

        try:
            return self._detailed_info_dict[sent_id]
        except KeyError as e:
            raise_from(InvalidIDError('Detailed information not found for '
                                      'sentence ID {}'.format(sent_id)), e)
开发者ID:larsyencken,项目名称:cjktools,代码行数:29,代码来源:tatoeba.py


示例20: assert_reset

 def assert_reset(self, asserted):
     """! @brief Assert or de-assert target reset line"""
     try:
         self._invalidate_cached_registers()
         self._link.assert_reset(asserted)
     except DAPAccess.Error as exc:
         six.raise_from(self._convert_exception(exc), exc)
开发者ID:flit,项目名称:pyOCD,代码行数:7,代码来源:cmsis_dap_probe.py



注:本文中的six.raise_from函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.reraise函数代码示例发布时间:2022-05-27
下一篇:
Python six.raise_函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap