Changeset 4158


Ignore:
Timestamp:
24 May 2009, 10:10:03 (16 years ago)
Author:
uli
Message:

Add a base for CSV imports.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • waeup/branches/ulif-rewrite/src/waeup/utils/importexport.py

    r4057 r4158  
    88from zope.interface import Interface
    99from waeup.interfaces import (IWAeUPObject, IWAeUPExporter, IWAeUPXMLExporter,
    10                               IWAeUPXMLImporter)
     10                              IWAeUPXMLImporter, IWAeUPCSVImporter)
    1111
    1212def readFile(f):
     
    8686        return obj
    8787
     88class CSVImporter(grok.Adapter):
     89    grok.context(IWAeUPObject)
     90    grok.provides(IWAeUPCSVImporter)
     91    grok.baseclass() # We don't want this base to be registered really.
     92    column_terms = [] # The column terms supported by this importer
     93   
     94    def __init__(self, context):
     95        self.context = context
     96   
     97    def doImport(self, filepath):
     98        pass
     99   
     100    def getData(self, filepath):
     101        result = readFile(open(filepath, 'rb'))
     102        return result
     103
     104    def validate(self, filepath):
     105        self.checkHeader(filepath)
     106        self.getData(filepath)
     107        return True
     108
     109    def checkHeader(self, filepath):
     110        missing = []
     111        headerline = ''
     112
     113        # Extract the header fields...
     114        for line in open(filepath, 'rb'):
     115            headerline = line
     116            if len(headerline.strip()) == 0:
     117                continue # Ignore leading empty lines...
     118            break # We only want the first line...
     119        tmpfile = StringIO(headerline)
     120        headerfields = readFile(tmpfile)[0]
     121
     122        # Find missing header fields...
     123        for key in self.column_terms:
     124            if key not in headerfields:
     125                missing.append(key)
     126        if len(missing):
     127            raise KeyError(
     128                'Validation Error: the follwing '
     129                'columns could not be found: %s' % (', '.join(missing))
     130                )
     131        return
Note: See TracChangeset for help on using the changeset viewer.