本文整理汇总了Python中ruamel.yaml.safe_load方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.safe_load方法的具体用法?Python yaml.safe_load怎么用?Python yaml.safe_load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ruamel.yaml
的用法示例。
在下文中一共展示了yaml.safe_load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def _init(cls):
if cls.package_name is None:
raise NotImplementedError("Package name not given")
if cls.spec_template_file is None:
raise NotImplementedError("Spec file not given")
loader = PackageLoader(cls.package_name, "")
env = Environment(loader=loader)
template = env.get_template(cls.spec_template_file)
tdict = yaml.safe_load(StringIO(template.render()))
tdict = jsonref.loads(json.dumps(tdict))
# TODO - Check if keys are present
cls.provider_spec = tdict["components"]["schemas"]["provider_spec"]
cls.Validator = StrictDraft7Validator(cls.provider_spec)
示例2: setup_logging
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def setup_logging(
default_path='./parameter/logger.yml',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = os.path.abspath(default_path)
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(os.path.abspath(path)):
with open(path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
示例3: get_resource_file
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def get_resource_file(sfile, sfile_type='yaml'):
''' return the service file '''
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if sfile_type == 'yaml':
# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
# pylint: disable=no-member
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif sfile_type == 'json':
contents = json.loads(contents)
return contents
示例4: collect_models
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def collect_models(self, in_bytes=False, b64encode=True):
model_buffers = {}
with open(self.define_meta_path, "r", encoding="utf-8") as fr:
define_index = yaml.safe_load(fr)
for component_name in define_index.get("model_proto", {}).keys():
for model_alias, model_proto_index in define_index["model_proto"][component_name].items():
component_model_storage_path = os.path.join(self.variables_data_path, component_name, model_alias)
for model_name, buffer_name in model_proto_index.items():
with open(os.path.join(component_model_storage_path, model_name), "rb") as fr:
buffer_object_serialized_string = fr.read()
if not in_bytes:
model_buffers[model_name] = self.parse_proto_object(buffer_name=buffer_name,
buffer_object_serialized_string=buffer_object_serialized_string)
else:
if b64encode:
buffer_object_serialized_string = base64.b64encode(buffer_object_serialized_string).decode()
model_buffers["{}.{}:{}".format(component_name, model_alias, model_name)] = buffer_object_serialized_string
return model_buffers
示例5: update_component_meta
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def update_component_meta(self, component_name, component_module_name, model_alias, model_proto_index):
"""
update meta info yaml
TODO: with lock
:param component_name:
:param component_module_name:
:param model_alias:
:param model_proto_index:
:return:
"""
with open(self.define_meta_path, "r", encoding="utf-8") as fr:
define_index = yaml.safe_load(fr)
with open(self.define_meta_path, "w", encoding="utf-8") as fw:
define_index["component_define"] = define_index.get("component_define", {})
define_index["component_define"][component_name] = define_index["component_define"].get(component_name, {})
define_index["component_define"][component_name].update({"module_name": component_module_name})
define_index["model_proto"] = define_index.get("model_proto", {})
define_index["model_proto"][component_name] = define_index["model_proto"].get(component_name, {})
define_index["model_proto"][component_name][model_alias] = define_index["model_proto"][component_name].get(model_alias, {})
define_index["model_proto"][component_name][model_alias].update(model_proto_index)
yaml.dump(define_index, fw, Dumper=yaml.RoundTripDumper)
示例6: compile
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def compile(self):
'''build an internal mapping of all nwo meta'''
migration_repo = self.g.get_repo('ansible-community/collection_migration')
ansible_repo = self.g.get_repo('ansible/ansible')
self._nwo = {}
self._flatmaps = set()
# Read in migration scenarios
for f in migration_repo.get_contents('scenarios/nwo'):
data = yaml.safe_load(base64.b64decode(f.content))
namespace, ext = os.path.splitext(f.name)
if ext != '.yml':
continue
for collection, content in data.items():
name = '%s.%s' % (namespace, collection)
if content.get('_options', {}).get('flatmap'):
self._flatmaps.add(name)
for ptype, paths in content.items():
for relpath in paths:
if ptype in ('modules', 'module_utils'):
path = 'lib/ansible/%s/%s' % (ptype, relpath)
else:
path = 'lib/ansible/plugins/%s/%s' % (ptype, relpath)
self._nwo[path] = name
示例7: load_yaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def load_yaml(filename):
"""Return object in yaml file."""
with open(filename) as myfile:
content = myfile.read()
if "win" in sys.platform:
content = content.replace("\\", "/")
try:
obj = yaml.safe_load(content)
# packed workflow, will be ignored later
if obj.get('$graph'):
obj = {}
# packed workflow, will be ignored later
# (it seems in some cases a packed workflow gives an ParserError, while
# in other cases it is loaded correctly)
except yaml.parser.ParserError:
obj = {}
return obj
示例8: run
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def run():
options.logging = 'info'
parse_command_line(args=[])
enable_pretty_logging()
with open(args.config, 'r') as f:
conf = yaml.safe_load(f)
parameters = conf['parameters']
AsyncIOMainLoop().install()
app = Application([
(r"/", MainHandler, dict(flag=conf['flag']))
], debug=args.debug)
app.listen(parameters['port'])
asyncio.get_event_loop().run_forever()
#-------------------------------------------------------------------------------
# SCRIPT
#-------------------------------------------------------------------------------
示例9: _update_from_file
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def _update_from_file(self, filename):
""" Helper method to update an existing configuration with the values from a file.
Loads a configuration file and replaces all values in the existing configuration
dictionary with the values from the file.
Args:
filename (str): The path and name to the configuration file.
"""
if os.path.exists(filename):
try:
with open(filename, 'r') as config_file:
yaml_dict = yaml.safe_load(config_file.read())
if yaml_dict is not None:
self._update_dict(self._config, yaml_dict)
except IsADirectoryError:
raise ConfigLoadError(
'The specified configuration file is a directory not a file')
else:
raise ConfigLoadError('The config file {} does not exist'.format(filename))
示例10: test_get_account_with_creds
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_get_account_with_creds(self):
os.environ["MY_USERNAME"] = "foo"
os.environ["MY_APIKEY"] = "bar"
config = yaml.safe_load(
"environments:\n"
" - name: {}\n"
' account: "{}"\n'
" rs_username_var: MY_USERNAME\n"
" rs_apikey_var: MY_APIKEY".format(self.environment, self.account)
)
account, role, username, apikey = run.get_account(config, self.environment)
del os.environ["MY_USERNAME"]
del os.environ["MY_APIKEY"]
self.assertEqual(account, self.account)
self.assertIsNone(role)
self.assertEqual(username, "foo")
self.assertEqual(apikey, "bar")
示例11: test_get_account_with_stage_creds
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_get_account_with_stage_creds(self):
os.environ["MY_USERNAME"] = "foo"
os.environ["MY_APIKEY"] = "bar"
config = yaml.safe_load(
"stages:\n"
" sandwhich:\n"
" environment: {env_name}\n"
"environments:\n"
" - name: {env_name}\n"
' account: "{account}"\n'
" rs_username_var: MY_USERNAME\n"
" rs_apikey_var: MY_APIKEY".format(
env_name=self.environment, account=self.account
)
)
account, role, username, apikey = run.get_account(config, None, "sandwhich")
del os.environ["MY_USERNAME"]
del os.environ["MY_APIKEY"]
self.assertEqual(account, self.account)
self.assertIsNone(role)
self.assertEqual(username, "foo")
self.assertEqual(apikey, "bar")
示例12: test_get_account_with_stage_creds_2
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_get_account_with_stage_creds_2(self):
os.environ["MY_USERNAME"] = "foo"
os.environ["MY_APIKEY"] = "bar"
config = yaml.safe_load(
"stages:\n"
" /.*/:\n"
" environment: {env_name}\n"
"environments:\n"
" - name: {env_name}\n"
' account: "{account}"\n'
" rs_username_var: MY_USERNAME\n"
" rs_apikey_var: MY_APIKEY".format(
env_name=self.environment, account=self.account
)
)
account, role, username, apikey = run.get_account(
config, None, "made-up-nonsense"
)
del os.environ["MY_USERNAME"]
del os.environ["MY_APIKEY"]
self.assertEqual(account, self.account)
self.assertIsNone(role)
self.assertEqual(username, "foo")
self.assertEqual(apikey, "bar")
示例13: test_import_json_config
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_import_json_config(self, *args):
stdin = sys.stdin
sys.stdin = StringIO(test_json_config)
config.main(["-c", TEST_CONFIG, "import"])
sys.stdin = stdin
with open(TEST_CONFIG, "rt") as f:
data = yaml.safe_load(f.read())
self.assertEqual(
data,
{
"stages": {
"/.*/": {"environment": "dev", "key": "dev-key"},
"prod": {"environment": "prod", "key": "prod-key"},
},
"config": {
"foo": "bar",
"password": {
"+dev": ":decrypt:ZGV2OmRldi1wYXNzd29yZA==",
"+prod": ":decrypt:cHJvZDpwcm9kLXBhc3N3b3Jk",
},
"nest": {"bird": "pigeon", "tree": "birch"},
},
},
)
示例14: test_render_yaml_config
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_render_yaml_config(self, *args):
stdout = sys.stdout
sys.stdout = StringIO()
with open(TEST_CONFIG, "wt") as f:
f.write(test_config_file)
config.main(["-c", TEST_CONFIG, "render", "dev"])
sys.stdout.seek(0)
data = sys.stdout.read()
sys.stdout = stdout
self.assertEqual(
yaml.safe_load(data),
{
"foo": "bar",
"password": "dev-password",
"nest": {"bird": "pigeon", "tree": "birch"},
},
)
示例15: test_render_yaml_config_custom
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import safe_load [as 别名]
def test_render_yaml_config_custom(self, *args):
stdout = sys.stdout
sys.stdout = StringIO()
with open(TEST_CONFIG, "wt") as f:
f.write(test_config_file)
config.main(["-c", TEST_CONFIG, "render", "foo"])
sys.stdout.seek(0)
data = sys.stdout.read()
sys.stdout = stdout
self.assertEqual(
yaml.safe_load(data),
{
"foo": "bar",
"password": "foo-password",
"nest": {"bird": "pigeon", "tree": "birch"},
},
)