1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
5 # http://www.apache.org/licenses/LICENSE-2.0
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
14 from collections import OrderedDict
15 from toscaparser.common.exception import ExceptionCollector
16 from toscaparser.common.exception import URLException
17 from toscaparser.utils.gettextutils import _
22 import urllib.request as urllib2
27 if hasattr(yaml, 'CSafeLoader'):
28 yaml_loader = yaml.CSafeLoader
30 yaml_loader = yaml.SafeLoader
33 def load_yaml(path, a_file=True):
36 f = codecs.open(path, encoding='utf-8', errors='strict') if a_file \
37 else urllib2.urlopen(path)
38 except urllib2.URLError as e:
39 if hasattr(e, 'reason'):
40 msg = (_('Failed to reach server "%(path)s". Reason is: '
42 % {'path': path, 'reason': e.reason})
43 ExceptionCollector.appendException(URLException(what=msg))
45 elif hasattr(e, 'code'):
46 msg = (_('The server "%(path)s" couldn\'t fulfill the request. '
47 'Error code: "%(code)s".')
48 % {'path': path, 'code': e.code})
49 ExceptionCollector.appendException(URLException(what=msg))
51 except Exception as e:
53 return yaml.load(f.read(), Loader=yaml_loader)
56 def simple_parse(tmpl_str):
58 tpl = yaml.load(tmpl_str, Loader=yaml_loader)
59 except yaml.YAMLError as yea:
60 ExceptionCollector.appendException(ValueError(yea))
67 def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
68 class OrderedLoader(Loader):
71 def construct_mapping(loader, node):
72 loader.flatten_mapping(node)
73 return object_pairs_hook(loader.construct_pairs(node))
75 OrderedLoader.add_constructor(
76 yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
78 return yaml.load(stream, OrderedLoader)
81 def simple_ordered_parse(tmpl_str):
83 tpl = ordered_load(tmpl_str)
84 except yaml.YAMLError as yea:
85 ExceptionCollector.appendException(ValueError(yea))