source: main/waeup.sirp/trunk/src/waeup/sirp/utils/importexport.py @ 6965

Last change on this file since 6965 was 4964, checked in by uli, 15 years ago

Remove unused imports.

  • Property svn:eol-style set to native
File size: 2.3 KB
Line 
1import csv
2import grok
3import cPickle
4import zope.xmlpickle
5from cStringIO import StringIO
6from zope.interface import Interface
7from waeup.sirp.interfaces import (IWAeUPObject, IWAeUPExporter,
8                                   IWAeUPXMLExporter, IWAeUPXMLImporter)
9
10def readFile(f):
11    """read a CSV file"""
12    headers = []
13    rows = []
14    f = csv.reader(f)
15    headers = f.next()
16    for line in f:
17        rows.append(line)
18    return (headers, rows)
19
20def writeFile(data):
21    writer = csv.writer(open("export.csv", "wb"))
22    writer.writerows(data)
23
24class Exporter(grok.Adapter):
25    """Export a WAeUP object as pickle.
26
27    This all-purpose exporter exports attributes defined in schemata
28    and contained objects (if the exported thing is a container).
29    """
30    grok.context(IWAeUPObject)
31    grok.provides(IWAeUPExporter)
32
33    def __init__(self, context):
34        self.context = context
35
36    def export(self, filepath=None):
37        if filepath is None:
38            filelike_obj = StringIO()
39        else:
40            filelike_obj = open(filepath, 'wb')
41        exported_obj = cPickle.dump(self.context, filelike_obj)
42        filelike_obj.close()
43        return filelike_obj
44
45class XMLExporter(grok.Adapter):
46    """Export a WAeUP object as XML.
47
48    This all-purpose exporter exports XML representations of pickable
49    objects.
50    """
51    grok.context(Interface)
52    grok.provides(IWAeUPXMLExporter)
53
54    def __init__(self, context):
55        self.context = context
56   
57    def export(self, filepath=None):
58        pickled_obj = cPickle.dumps(self.context)
59        result = zope.xmlpickle.toxml(pickled_obj)
60        if filepath is None:
61            filelike_obj = StringIO()
62        else:
63            filelike_obj = open(filepath, 'wb')
64        filelike_obj.write(result)
65        filelike_obj.seek(0)
66        return filelike_obj
67
68class XMLImporter(grok.Adapter):
69    """Import a WAeUP object from XML.
70    """
71    grok.context(Interface)
72    grok.provides(IWAeUPXMLImporter)
73
74    def __init__(self, context):
75        self.context = context
76   
77    def doImport(self, filepath):
78        xml = None
79        if isinstance(filepath, basestring):
80            xml = open(filepath, 'rb').read()
81        else:
82            xml = filepath.read()
83        obj = zope.xmlpickle.loads(xml)
84        return obj
Note: See TracBrowser for help on using the repository browser.