示例#1
0
 def represent_mapping(self, tag, mapping, flow_style=None):
     value = []
     node = MappingNode(tag, value, flow_style=flow_style)
     if self.alias_key is not None:
         self.represented_objects[self.alias_key] = node
     best_style = True
     if hasattr(mapping, "items"):
         mapping = list(mapping.items())
         if self.sort_keys:
             try:
                 # all code is directly from the base class except this sorted
                 mapping = sorted(mapping, key=sort_key)
             except TypeError:
                 pass
     for item_key, item_value in mapping:
         node_key = self.represent_data(item_key)
         node_value = self.represent_data(item_value)
         if not (isinstance(node_key, ScalarNode) and not node_key.style):
             best_style = False
         if not (isinstance(node_value, ScalarNode) and not node_value.style):
             best_style = False
         value.append((node_key, node_value))
     if flow_style is None:
         if self.default_flow_style is not None:
             node.flow_style = self.default_flow_style
         else:
             node.flow_style = best_style
     return node
示例#2
0
 def represent_mapping(self, tag, mapping, flow_style=None):
     value = []
     node = MappingNode(tag, value, flow_style=flow_style)
     if self.alias_key is not None:
         self.represented_objects[self.alias_key] = node
     best_style = True
     if hasattr(mapping, 'items'):
         mapping = list(mapping.items())
         if not isinstance(mapping, OrderedDict):
             mapping.sort()
     for item_key, item_value in mapping:
         node_key = self.represent_data(item_key)
         node_value = self.represent_data(item_value)
         if not (isinstance(node_key, ScalarNode) and not node_key.style):
             best_style = False
         if not (isinstance(node_value, ScalarNode)
                 and not node_value.style):
             best_style = False
         value.append((node_key, node_value))
     if flow_style is None:
         if self.default_flow_style is not None:
             node.flow_style = self.default_flow_style
         else:
             node.flow_style = best_style
     return node
def dupe_node():
    tag = 'tag:yaml.org,2002:map'
    scalar_tag = 'tag:yaml.org,2002:str'
    mark = Mark(tag, 0, 0, 0, None, None)
    node = MappingNode(tag, [
        (ScalarNode(tag=scalar_tag, value='bar', start_mark=mark),
         ScalarNode(tag=scalar_tag, value='baz', start_mark=mark)),
        (ScalarNode(tag=scalar_tag, value='bar', start_mark=mark),
         ScalarNode(tag=scalar_tag, value='qux', start_mark=mark)),
    ],
                       start_mark=mark)

    return node
示例#4
0
def __represent_yaml_map_ordered(self, mapping, flow_style=None):
    value = []
    node = MappingNode(__YAML_MAP_TAG, value, flow_style=flow_style)
    if self.alias_key is not None:
        self.represented_objects[self.alias_key] = node
    best_style = True
    if hasattr(mapping, 'items'):
        mapping = mapping.items()
    for item_key, item_value in mapping:
        node_key = self.represent_data(item_key)
        node_value = self.represent_data(item_value)
        if not (isinstance(node_key, ScalarNode) and not node_key.style):
            best_style = False
        if not (isinstance(node_value, ScalarNode) and not node_value.style):
            best_style = False
        value.append((node_key, node_value))
    if flow_style is None:
        if self.default_flow_style is not None:
            node.flow_style = self.default_flow_style
        else:
            node.flow_style = best_style
    return node
示例#5
0
def represent_mapping(dumper, mapping, flow_style=None):

    # override to dump map with item in any types
    value = []
    tag = u'tag:yaml.org,2002:map'
    node = MappingNode(tag, value, flow_style=flow_style)

    if dumper.alias_key is not None:
        dumper.represented_objects[dumper.alias_key] = node

    # there is the change
    # ex: [u'hello', '中国'].sort() raises an error

    # if hasattr(mapping, 'items'):
    #     mapping = mapping.items()
    #     mapping.sort()

    best_style = True
    for item_key, item_value in mapping.items():

        node_key = dumper.represent_data(item_key)
        node_value = dumper.represent_data(item_value)

        if not (isinstance(node_key, ScalarNode) and not node_key.style):
            best_style = False

        if not (isinstance(node_value, ScalarNode) and not node_value.style):
            best_style = False

        value.append((node_key, node_value))

    if flow_style is None:
        if dumper.default_flow_style is not None:
            node.flow_style = dumper.default_flow_style
        else:
            node.flow_style = best_style

    return node
def represent_mapping(dumper, mapping, flow_style=None):

    # override to dump map with item in any types
    value = []
    tag = u'tag:yaml.org,2002:map'
    node = MappingNode(tag, value, flow_style=flow_style)

    if dumper.alias_key is not None:
        dumper.represented_objects[dumper.alias_key] = node

    # there is the change
    # ex: [u'hello', '中国'].sort() raises an error

    # if hasattr(mapping, 'items'):
    #     mapping = mapping.items()
    #     mapping.sort()

    best_style = True
    for item_key, item_value in mapping.items():

        node_key = dumper.represent_data(item_key)
        node_value = dumper.represent_data(item_value)

        if not (isinstance(node_key, ScalarNode) and not node_key.style):
            best_style = False

        if not (isinstance(node_value, ScalarNode) and not node_value.style):
            best_style = False

        value.append((node_key, node_value))

    if flow_style is None:
        if dumper.default_flow_style is not None:
            node.flow_style = dumper.default_flow_style
        else:
            node.flow_style = best_style

    return node
示例#7
0
 def represent_mapping(self, tag, mapping, flow_style=None):
     value = []
     node = MappingNode(tag, value, flow_style=flow_style)
     if self.alias_key is not None:
         self.represented_objects[self.alias_key] = node
     best_style = True
     if hasattr(mapping, 'items'):
         mapping = list(mapping.items())
         if not isinstance(mapping, OrderedDict):
             mapping.sort()
     for item_key, item_value in mapping:
         node_key = self.represent_data(item_key)
         node_value = self.represent_data(item_value)
         if not (isinstance(node_key, ScalarNode) and not node_key.style):
             best_style = False
         if not (isinstance(node_value, ScalarNode) and not node_value.style):
             best_style = False
         value.append((node_key, node_value))
     if flow_style is None:
         if self.default_flow_style is not None:
             node.flow_style = self.default_flow_style
         else:
             node.flow_style = best_style
     return node
示例#8
0
def model_representer(dumper, obj):
  node = MappingNode(tag=u'tag:yaml.org,2002:map', value=[], flow_style=False)
  for column in obj.__table__.columns:
    if isinstance(column.type, String):
      node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                         dumper.represent_scalar(tag=u'tag:yaml.org,2002:str', value=unicode(getattr(obj, column.name)), style='"')))
    elif isinstance(column.type, Integer):
      node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                         dumper.represent_scalar(tag=u'tag:yaml.org,2002:int', value=unicode(getattr(obj, column.name)), style='')))
    elif isinstance(column.type, Float):
      node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                         dumper.represent_scalar(tag=u'tag:yaml.org,2002:float', value=unicode(getattr(obj, column.name)), style='')))
    elif isinstance(column.type, Boolean):
      node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                         dumper.represent_scalar(tag=u'tag:yaml.org,2002:bool', value=unicode(getattr(obj, column.name)), style='')))
    else:
      raise TypeError("No scalar representation is implemented for SQLAlchemy column type {col_type}".format(column.type))

  # This code is to print out the attributes inherited from the class Device by the AnalogDevice and DigitalDevice
  if (hasattr(obj.__class__.__bases__[0],'__tablename__')):
    if (obj.__class__.__bases__[0].__tablename__ == "devices"):
      for column in obj.__class__.__bases__[0].__table__.columns:
        if (column.name != "type"):
          if isinstance(column.type, String):
            node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                               dumper.represent_scalar(tag=u'tag:yaml.org,2002:str', value=unicode(getattr(obj, column.name)), style='"')))
          elif isinstance(column.type, Integer):
            node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                               dumper.represent_scalar(tag=u'tag:yaml.org,2002:int', value=unicode(getattr(obj, column.name)), style='')))
          elif isinstance(column.type, Float):
            node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                               dumper.represent_scalar(tag=u'tag:yaml.org,2002:float', value=unicode(getattr(obj, column.name)), style='')))
          elif isinstance(column.type, Boolean):
            node.value.append((ScalarNode(tag=u'tag:yaml.org,2002:str', value=column.name), 
                               dumper.represent_scalar(tag=u'tag:yaml.org,2002:bool', value=unicode(getattr(obj, column.name)), style='')))
          else:
            raise TypeError("No scalar representation is implemented for SQLAlchemy column type {col_type}".format(column.type))
 
  return node
示例#9
0
    ScalarView:
    lambda v: v.node,
    list:
    lambda l: SequenceNode(Tag.SEQUENCE.value, [node(i) for i in l]),
    tuple:
    lambda t: SequenceNode(Tag.SEQUENCE.value, [node(i) for i in t]),
    str:
    lambda s: ScalarNode(Tag.STRING.value, str(s)),
    bool:
    lambda b: ScalarNode(Tag.BOOL.value, str(b)),
    int:
    lambda i: ScalarNode(Tag.INT.value, str(i)),
    float:
    lambda f: ScalarNode(Tag.FLOAT.value, str(f)),
    dict:
    lambda d: MappingNode(Tag.MAPPING.value, [(node(k), node(v))
                                              for k, v in d.items()])
}


def node(value: Any) -> Node:
    return COERCIONS[type(value)](value)


def load(name: str, value: Any, *allowed: Tag) -> SequenceView:
    if isinstance(value, str):
        value = StringIO(value)
        value.name = name
    result = view(SequenceNode(Tag.SEQUENCE.value, list(compose_all(value))),
                  ViewMode.PYTHON)
    for r in view(result, ViewMode.NODE):
        if r.tag not in allowed:
示例#10
0
def scalars_to_strings(node, state = BASE):
  r'''Turn scalars into strings, except for dict keys and !stubbly content.
Also turn !stubbly/quote-as-strings content into strings.

    >>> document = """ 
    ...   number: 5
    ...   boolean: on
    ...   null:
    ...   unquoted: hello
    ...   quoted: 'hello'
    ...   sequence:
    ...     - 1 # SHOULD be converted to a string
    ...     - 2: [3, 4] # 2 shoud NOT be converted to a string
    ...   $code:
    ...   - 4 # should NOT be converted to a string
    ...   - $quote-as-strings:
    ...     - 5: 6 # should ALL be converted to a string
    ...     - $code: 6 # SHOULD be converted to strings
    ...   ?
    ... """
    >>> loader = yaml.Loader(document)
    >>> loader.check_data()
    True
    >>> node = loader.get_node()
    >>> stringified = scalars_to_strings(node)
    >>> print(yaml.serialize(stringified).strip())
    number: '5'
    boolean: 'on'
    null: ''
    unquoted: hello
    quoted: 'hello'
    sequence:
    - '1'
    - 2:
      - '3'
      - '4'
    $code:
    - 4
    - $quote-as-strings:
      - '5': '6'
      - '$code': '6'
    ?
    : ''
  '''
  tag = node.tag
  value = node.value

  if type(node) is SequenceNode:
    return SequenceNode(
      tag = tag,
      value = [scalars_to_strings(item, state) for item in value]
    )

  if type(node) is MappingNode:
    return MappingNode(
      tag = tag,
      value = [mapping_item_to_strings(item, state) for item in value]
    )

  if (tag == STRING_TAG or
      state is SYMBOL or
      (state is BASE and tag.startswith(STUBBLY_TAG_PREFIX))):
    return node

  return ScalarNode(
    tag = STRING_TAG,
    value = value
  )