:mod:`waeup.utils.csvimport` -- CSV file importers ************************************************** .. module:: waeup.utils.csvimport Components for importing CSV files. :Test-Layer: unit Because CSV importers make use of components registered with the Zope Component Architecture (ZCA), we first have to grok the `waeup` package. This happens automatically in real-world use: >>> import grok >>> grok.testing.grok('waeup') Importing from CSV files ------------------------ We create a facultycontainer, which we want to populate with some CSV data afterwards: >>> from waeup.university.facultycontainer import FacultyContainer >>> mycontainer = FacultyContainer() Next, we create a CSV file we want to import: >>> open('myfaculties.csv', 'wb').write( ... """code,review_state,title,title_prefix ... AGR,static,Agriculture,faculty ... ART,static,Arts,faculty ... DEN,static,Dentistry,faculty ... """) We get a suitable importer by asking for a multi-adapter to our file and IWAeUPCSVExporter (see section above, the importexport module and the `waeup.csvfile` README for details): >>> from waeup.csvfile import getCSVFile >>> from waeup.interfaces import IWAeUPCSVImporter >>> from zope.component import getMultiAdapter >>> importer = getMultiAdapter((getCSVFile('myfaculties.csv'), ... mycontainer), ... IWAeUPCSVImporter) >>> importer This importer complies with the IWAeUPCSVImporter interface: >>> from waeup.utils.csvimport import FacultyCSVImporter >>> IWAeUPCSVImporter.implementedBy(FacultyCSVImporter) True >>> from zope.interface.verify import verifyClass >>> verifyClass(IWAeUPCSVImporter, FacultyCSVImporter) True The container is still empty: >>> len(mycontainer) 0 Now we can easily import the data: >>> importer.doImport() The container is now filled: >>> len(mycontainer) 3 >>> print [(x.code, x.title) for x in list(mycontainer.values())] [('AGR', 'Agriculture'), ('ART', 'Arts'), ('DEN', 'Dentistry')] Clean up: >>> import os >>> os.unlink('myfaculties.csv')