本文整理汇总了Python中yaml.SafeLoader类的典型用法代码示例。如果您正苦于以下问题:Python SafeLoader类的具体用法?Python SafeLoader怎么用?Python SafeLoader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SafeLoader类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __load
def __load(self, rules_data: str) -> None:
"""
loads a yaml str, serializes and normalized the rule data. Then assigns the rule data to properties.
:param config_file: A :string: loaded from a yaml file.
"""
if not isinstance(rules_data, str):
raise TypeError('rules_data must be a str.')
try:
data = SafeLoader(rules_data).get_data()
if data is None:
raise AttributeError('The rules must have data in it.')
data = normalize_keys(data, snake_case=False)
for key, value in data.items():
variable_name = '_{0}'.format(key)
if hasattr(self, variable_name):
setattr(self, variable_name, value)
else:
raise AttributeError('{0} isn\'t a valid rule attribute.'.format(key))
except YAMLError as e:
if hasattr(e, 'problem_mark'):
raise SyntaxError(
"There is a syntax error in the rules line: {0} column: {1}".format(
e.problem_mark.line,
e.problem_mark.column
)
)
else:
raise SyntaxError("There is a syntax error in the rules.")
开发者ID:TuneOSS,项目名称:customs,代码行数:32,代码来源:rules.py
示例2: fix_yaml_loader
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,代码行数:11,代码来源:__init__.py
示例3: _load_user_settings
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,代码行数:53,代码来源:config.py
示例4: _handle_quirks
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,代码行数:14,代码来源:cbapi2.py
示例5: get_config_yaml
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,代码行数:17,代码来源:createInstance.py
示例6: _do_loads
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,代码行数:17,代码来源:loader.py
示例7: __init__
def __init__(self, context, stream, iter_entry_points=iter_entry_points):
self.context = context
for point in list(iter_entry_points(self.EP_GROUP)):
try:
directive = point.load()
if point.name.startswith('tag:'):
directive_name = point.name
else:
directive_name = '!' + point.name
self.add_constructor(directive_name, wrap_directive(directive))
except ImportError:
logging.info(
'Could not import repoze.configuration.directive '
'entry point "%s"' % point)
self.add_constructor('tag:yaml.org,2002:str', self.interpolate_str)
SafeLoader.__init__(self, stream)
while self.check_data():
self.get_data()
开发者ID:repoze,项目名称:repoze.configuration,代码行数:18,代码来源:loader.py
示例8: construct_yaml_str
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,代码行数:30,代码来源:yaml_config.py
示例9: yaml_load
# -*- 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,代码行数:17,代码来源:yaml.py
注:本文中的yaml.SafeLoader类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论