コード例 #1
0
    def __call__(self, Lines=None):
        """Returns the record constructed from Lines, or self.Lines"""
        if Lines is None:
            Lines = self.Lines
        result = self.Constructor()
        fieldmap = self.FieldMap
        aka = result.unalias

        splitter = self.LabelSplitter
        for line in Lines:
            # find out how many items we got, setting key and val appropiately
            items = list(splitter(line))
            num_items = len(items)
            if num_items == 2:  # typical case: key-value pair
                raw_field, val = items
            elif num_items > 2:
                raw_field = items[0]
                val = items[1:]
            elif len(items) == 1:
                raw_field, val = items[0], None
            elif not items:  # presumably had line with just a delimiter?
                continue
            # figure out if we know the field under its original name or as
            # an alias
            if raw_field in fieldmap:
                field, mapper = raw_field, fieldmap[raw_field]
            else:
                new_field = aka(raw_field)
                if new_field in fieldmap:
                    field, mapper = new_field, fieldmap[new_field]
                else:
                    if self.Strict:
                        raise FieldError("Got unrecognized field %s" %
                                         (raw_field, ))
                    else:
                        identity_setter(result, raw_field, val)
                    continue
            # if we found the field in the fieldmap, apply the correct function
            try:
                mapper(result, field, val)
            except:  # Warning: this is a catchall for _any_ exception,
                # and may mask what's actually going wrong.
                if self.Strict:
                    raise FieldError("Could not handle line %s" % (line, ))
        return result
コード例 #2
0
def raise_unknown_field(field, data):
    """Raises a FieldError, displaying the offending field and data."""
    raise FieldError("Got unknown field %s with data %s" % (field, data))
コード例 #3
0
 def parser(line):
     items = splitter(line)
     if len(items) != len(fields):
         raise FieldError("Expected %s items but got %s: %s" %
                          (len(fields), len(items), items))
     return dict(zip(fields, items))