summaryrefslogtreecommitdiffstats
path: root/admin/lib/csvstore.py
blob: 58a305603471e074ecc16fd356284d165a68dbd6 (plain)
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
from UserDict import IterableUserDict
from StringIO import StringIO

import csv

class Storage(IterableUserDict):
    def __init__(self, encapsulation):
        self.encapsulation = encapsulation
        self.encapsulation.begin_transaction()
        try:
            stored = {x[0]: [x[1], x[2]] 
                for x in csv.reader(StringIO(self.encapsulation.data))}
        except IOError:
            stored = {}
        IterableUserDict.__init__(self, stored)
    def sync(self):
        f = StringIO()
        csv.writer(f).writerows(
            [c, u, name] for c, (u, name) in self.data.iteritems())
        
        self.encapsulation.data = f.getvalue()
        self.encapsulation.end_transaction()
        f.close()
        
        self.encapsulation.begin_transaction()
    def __del__(self):
        self.sync()
    def __setitem__(self, k, v):
        IterableUserDict.__setitem__(self, k, v)
        self.sync()
    def __delitem__(self, k):
        IterableUserDict.__delitem__(self, k)
        self.sync()