1 | import re |
---|
2 | import csv |
---|
3 | import grok |
---|
4 | import cPickle |
---|
5 | import zope.xmlpickle |
---|
6 | from cStringIO import StringIO |
---|
7 | from xml.dom.minidom import Document, getDOMImplementation |
---|
8 | from zope.interface import Interface |
---|
9 | from waeup.interfaces import (IWAeUPObject, IWAeUPExporter, IWAeUPXMLExporter, |
---|
10 | IWAeUPXMLImporter) |
---|
11 | |
---|
12 | def 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 | |
---|
22 | def writeFile(data): |
---|
23 | writer = csv.writer(open("export.csv", "wb")) |
---|
24 | writer.writerows(data) |
---|
25 | |
---|
26 | class 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 | |
---|
47 | class 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 | |
---|
70 | class 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 | |
---|