当前位置: 首页>>代码示例>>Python>>正文


Python SafeLoader.add_constructor方法代码示例

本文整理汇总了Python中yaml.SafeLoader.add_constructor方法的典型用法代码示例。如果您正苦于以下问题:Python SafeLoader.add_constructor方法的具体用法?Python SafeLoader.add_constructor怎么用?Python SafeLoader.add_constructor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yaml.SafeLoader的用法示例。


在下文中一共展示了SafeLoader.add_constructor方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fix_yaml_loader

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
def fix_yaml_loader():
    """Ensure that any string read by yaml is represented as unicode."""
    from yaml import Loader, SafeLoader

    def construct_yaml_str(self, node):
        # Override the default string handling function
        # to always return unicode objects
        return self.construct_scalar(node)

    Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
    SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
开发者ID:githubclj,项目名称:rasa_nlu,代码行数:13,代码来源:__init__.py

示例2: _load_user_settings

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
    def _load_user_settings(self):
        """Load user settings from config file."""
        successful = _ensure_file(self.config_file)

        if not successful:
            LOG.error("Unable to load user config file.")
            return

        self.subscriptions = []

        # Python 2/PyPy shim, per
        # https://stackoverflow.com/questions/2890146/how-to-force-pyyaml-to-load-strings-as-unicode-objects
        # Override the default string handling function to always return unicode objects.
        def construct_yaml_str(self, node):
            """Override to force PyYAML to handle unicode on Python 2."""
            return self.construct_scalar(node)

        SafeLoader.add_constructor("tag:yaml.org,2002:python/unicode", construct_yaml_str)

        with open(self.config_file, "r") as stream:
            LOG.debug("Opening config file to retrieve settings.")
            yaml_settings = yaml.safe_load(stream)

        pretty_settings = yaml.dump(yaml_settings, width=1, indent=4)
        LOG.debug("Settings retrieved from user config file: %s", pretty_settings)

        if yaml_settings is not None:

            # Update self.settings, but only currently valid settings.
            for name, value in yaml_settings.items():
                if name == "subscriptions":
                    pass
                elif name not in self.settings:
                    LOG.debug("Setting %s is not a valid setting, ignoring.", name)
                else:
                    self.settings[name] = value

            fail_count = 0
            for i, yaml_sub in enumerate(yaml_settings.get("subscriptions", [])):
                sub = Subscription.Subscription.parse_from_user_yaml(yaml_sub, self.settings)

                if sub is None:
                    LOG.debug("Unable to parse user YAML for sub # %s - something is wrong.",
                              i + 1)
                    fail_count += 1
                    continue

                self.subscriptions.append(sub)

            if fail_count > 0:
                LOG.error("Some subscriptions from config file couldn't be parsed - check logs.")

        return True
开发者ID:andrewmichaud,项目名称:puckfetcher,代码行数:55,代码来源:config.py

示例3: _handle_quirks

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
    def _handle_quirks(self):
        if self._unicode_quirk:
            self._logger.debug('Enabling unicode quirk')

            def construct_yaml_str(self, node):
                try:
                    rawdata = b''.join([chr(ord(x)) for x in self.construct_scalar(node)])
                    return rawdata.decode('utf8')
                except ValueError:
                    # apparently sometimes the data is already correctly encoded
                    return self.construct_scalar(node)

            Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
            SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
开发者ID:redcanaryco,项目名称:cbapi2,代码行数:16,代码来源:cbapi2.py

示例4: get_config_yaml

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
def get_config_yaml( path_config=os.path.dirname(os.path.realpath(__file__)) + "/../config.d/config.yaml", name_config="openstack"):
    import yaml
    from yaml import Loader, SafeLoader

    def construct_yaml_str(self, node):
        # Override the default string handling function 
        # to always return unicode objects
        return self.construct_scalar(node)

    Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
    SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)

    f = open(path_config)
    # use safe_load instead load
    dataMap = yaml.load(f)[name_config]
    f.close()
    return dataMap
开发者ID:fessoga5,项目名称:openstack-ops-scripts,代码行数:19,代码来源:createInstance.py

示例5: _do_loads

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
    def _do_loads(self, s, *args, **kwargs):
        import yaml
        from yaml import Loader, SafeLoader

        # Force Unicode string output according to this SO question
        # 2890146/how-to-force-pyyaml-to-load-strings-as-unicode-objects
        def construct_yaml_str(self, node):
            # Override the default string handling function
            # to always return unicode objects
            return self.construct_scalar(node)

        _STR_TAG = 'tag:yaml.org,2002:str'
        Loader.add_constructor(_STR_TAG, construct_yaml_str)
        SafeLoader.add_constructor(_STR_TAG, construct_yaml_str)

        # TODO: optionally utilize C acceleration if available
        return yaml.load(s, *args, **kwargs)
开发者ID:xen0n,项目名称:weiyu,代码行数:19,代码来源:loader.py

示例6: construct_yaml_str

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
import os

from path import path

# https://stackoverflow.com/questions/2890146/how-to-force-pyyaml-to-load-strings-as-unicode-objects
from yaml import Loader, SafeLoader


def construct_yaml_str(self, node):
    """
    Override the default string handling function
    to always return unicode objects
    """
    return self.construct_scalar(node)
Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)

# SERVICE_VARIANT specifies name of the variant used, which decides what YAML
# configuration files are read during startup.
SERVICE_VARIANT = os.environ.get('SERVICE_VARIANT', None)

# CONFIG_ROOT specifies the directory where the YAML configuration
# files are expected to be found. If not specified, use the project
# directory.
CONFIG_ROOT = path(os.environ.get('CONFIG_ROOT', ENV_ROOT))

# CONFIG_PREFIX specifies the prefix of the YAML configuration files,
# based on the service variant. If no variant is use, don't use a
# prefix.
CONFIG_PREFIX = SERVICE_VARIANT + "." if SERVICE_VARIANT else ""
开发者ID:189140879,项目名称:edx-platform,代码行数:32,代码来源:yaml_config.py

示例7: yaml_load

# 需要导入模块: from yaml import SafeLoader [as 别名]
# 或者: from yaml.SafeLoader import add_constructor [as 别名]
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals

from yaml import safe_load, safe_dump, SafeLoader


SafeLoader.add_constructor('tag:yaml.org,2002:python/unicode', SafeLoader.construct_yaml_str)


def yaml_load(stream):
    """Loads a dictionary from a stream"""
    return safe_load(stream)


def yaml_dump(data, stream=None):
    """Dumps an object to a YAML string"""
    return safe_dump(data, stream=stream, default_flow_style=False)
开发者ID:Anaconda-Platform,项目名称:anaconda-client,代码行数:19,代码来源:yaml.py


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