-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsheet.py
More file actions
87 lines (68 loc) · 2.51 KB
/
Copy pathsheet.py
File metadata and controls
87 lines (68 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import copy
import BTrees.IOBTree
class Sheet(object):
"""
An abstract representation of a single sheet of a spreadsheet.
"""
def __init__(self, columns=None, root_id="", name=None):
self.id_columns = []
self.columns = columns if columns else []
self.titles = {}
self._lines = []
self.root_id = root_id
self.name = name
@property
def lines(self):
return self._lines
@property
def line_count(self):
return len(self._lines)
def add_field(self, field, id_field=False):
columns = self.id_columns if id_field else self.columns
if field not in columns:
columns.append(field)
def append(self, item):
self.add_field(item)
def __iter__(self):
if self.root_id:
yield self.root_id
for column in self.id_columns:
yield column
for column in self.columns:
yield column
def append_line(self, flattened_dict):
self._lines.append(flattened_dict)
class PersistentSheet(Sheet):
"""
A sheet that is persisted in ZODB database.
"""
def __init__(self, columns=None, root_id="", name=None, connection=None):
super().__init__(columns=columns, root_id=root_id, name=name)
self.connection = connection
self.index = 0
# Integer key and object value btree. Store sequential index in order to preserve input order.
connection.root.sheet_store[self.name] = BTrees.IOBTree.BTree()
@property
def lines(self):
# btrees iterate in key order.
for key, value in self.connection.root.sheet_store[self.name].items():
# 5000 chosen by trial and error. The written row
# data is removed from memory as is no loner needed.
# All new sheets clear out previous sheets data from memory.
if key % 5000 == 0:
self.connection.cacheMinimize()
yield value
@property
def line_count(self):
return self.index
def append_line(self, flattened_dict):
self.connection.root.sheet_store[self.name][self.index] = flattened_dict
self.index += 1
@classmethod
def from_sheet(cls, sheet, connection):
instance = cls(name=sheet.name, connection=connection)
instance.id_columns = copy.deepcopy(sheet.id_columns)
instance.columns = copy.deepcopy(sheet.columns)
instance.titles = copy.deepcopy(sheet.titles)
instance.root_id = sheet.root_id
return instance