source: waeup/branches/ulif-rewrite/src/waeup/utils/importexport.py @ 4050

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

First simple implementation of a gerneral purpose importer.

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