Statistics
| Branch: | Tag: | Revision:

root / pithos / backends / dummy.py @ 4adb68b8

History | View | Annotate | Download (7.3 kB)

1
import os
2
import sqlite3
3
import json
4

    
5
basepath = '/Users/butters/src/pithos/backends/content' #full path
6
if not os.path.exists(basepath):
7
    os.makedirs(basepath)
8
db = '/'.join([basepath, 'db'])
9
con = sqlite3.connect(db)
10
# Create tables
11
print 'Creating tables....'
12
sql = '''create table if not exists objects(name varchar(2560))'''
13
print sql
14
con.execute(sql)
15
# Save (commit) the changes
16
con.commit()
17
    
18
def create_container(name):
19
    """ creates a new container with the given name
20
    if it doesn't exists under the basepath """
21
    fullname = '/'.join([basepath, name])    
22
    if not os.path.exists(fullname):
23
        os.chdir(basepath)
24
        os.mkdir(name)
25
    else:
26
        raise NameError('Container already exists')
27
    return
28

    
29
def delete_container(name):
30
    """ deletes the container with the given name
31
        if it exists under the basepath """
32
    fullname = '/'.join([basepath, name])    
33
    if not os.path.exists(fullname):
34
        raise NameError('Container does not exist')
35
    if not list_objects(name):
36
        raise Error('Container is not empty')
37
    else:
38
        os.chdir(basepath)
39
        os.rmdir(name)
40
    return
41

    
42
def get_container_meta(name):
43
    """ returns a dictionary with the container metadata """
44
    fullname = '/'.join([basepath, name])
45
    if not os.path.exists(fullname):
46
        raise NameError('Container does not exist')
47
    contents = os.listdir(fullname) 
48
    count = len(contents)
49
    size = sum(os.path.getsize('/'.join([basepath, name, objectname])) for objectname in contents)
50
    return {'name': name, 'count': count, 'bytes': size}
51

    
52
def list_containers():
53
    return os.listdir(basepath) 
54

    
55
def list_objects(container, prefix='', delimiter=None):
56
    dir = '/'.join([basepath, container])
57
    if not os.path.exists(dir):
58
        raise NameError('Container does not exist')
59
    search_str = ''
60
    if prefix:
61
        search_str = '/'.join([search_str, prefix])
62
    #if delimiter:
63
    if None:
64
        search_str = ''.join(['%', search_str, '%', delimiter])
65
        print search_str
66
        c = con.execute('select * from objects where name like ''?'' order by name', (search_str,))
67
    else:
68
        search_str = ''.join(['%', search_str, '%'])
69
        print search_str
70
        c = con.execute('select * from objects where name like ''?'' order by name', (search_str,))
71
    l = []
72
    for row in c.fetchall():
73
        s = ''
74
        print row[0]
75
        rest = str(row[0]).split(prefix)[1]
76
        print rest
77
        #if delimiter:
78
        #    rest = rest.partition(delimiter)[0]
79
        #print rest
80
        folders = rest.split('/')[:-1]
81
        for folder in folders:
82
            path = ''.join([s, folder, '/'])
83
            if path not in l:
84
                l.append(path)
85
            s = ''.join([s, folder, '/'])
86
        l.append(rest)
87
    return l
88

    
89
def get_object_meta(container, name):
90
    dir = '/'.join([basepath, container])
91
    if not os.path.exists(dir):
92
        raise NameError('Container does not exist')
93
    else:
94
        os.chdir(dir)
95
    location = __get_object_linkinfo('/'.join([container, name]))
96
    location = '.'.join([location, 'meta'])
97
    f = open(location, 'r')
98
    data = json.load(f)
99
    f.close()
100
    return data
101

    
102
def get_object_data(container, name, offset=0, length=-1):
103
    dir = '/'.join([basepath, container])
104
    if not os.path.exists(dir):
105
        raise NameError('Container does not exist')
106
    else:
107
        os.chdir(dir)
108
    location = __get_object_linkinfo('/'.join([container, name]))
109
    f = open(location, 'r')
110
    if offset:
111
        f.seek(offset)
112
    data = f.read(length)
113
    f.close()
114
    return data
115

    
116
def update_object(container, name, data):
117
    dir = '/'.join([basepath, container])
118
    if not os.path.exists(dir):
119
        raise NameError('Container does not exist')
120
    try:
121
        location = __get_object_linkinfo('/'.join([container, name]))
122
    except NameError:
123
        # new object
124
        location = str(__save_linkinfo('/'.join([container, name])))
125
        print ':'.join(['Creating new location', location])
126
    __store_data(location, container, data)
127
    return
128

    
129
def update_object_meta(container, name, meta):
130
    dir = '/'.join([basepath, container])
131
    if not os.path.exists(dir):
132
        raise NameError('Container does not exist')
133
    try:
134
        location = __get_object_linkinfo('/'.join([container, name]))
135
    except NameError:
136
        # new object
137
        location = str(__save_linkinfo('/'.join([container, name])))
138
        print ':'.join(['Creating new location', location])
139
    __store_metadata(location, container, meta)
140
    return
141

    
142
def copy_object(src_container, src_name, dest_container, dest_name, meta):
143
    fullname = '/'.join([basepath, dest_container])    
144
    if not os.path.exists(fullname):
145
        raise NameError('Destination container does not exist')
146
    update_object(dest_container, dest_name, get_object_data(src_container, src_name))
147
    src_object_meta = get_object_meta(src_container, src_name)
148
    if (type(src_object_meta) == types.DictType):
149
        distinct_keys = [k for k in src_object_meta.keys() if k not in meta.keys()]
150
        for k in distinct_keys:
151
            meta[k] = src_object_meta[k]
152
            update_object_meta(dest_container, dest_name, meta)
153
    else:
154
        update_object_meta(dest_container, dest_name, meta)
155
    return
156

    
157
def delete_object(container, name):
158
    return
159

    
160
def __store_metadata(location, container, meta):
161
    dir = '/'.join([basepath, container])
162
    if not os.path.exists(dir):
163
        raise NameError('Container does not exist')
164
    else:
165
        os.chdir(dir)
166
    location = '.'.join([location, 'meta'])
167
    f = open(location, 'w')
168
    data = json.dumps(meta)
169
    f.write(data)
170
    f.close()
171

    
172
def __store_data(location, container, data):
173
    dir = '/'.join([basepath, container])
174
    if not os.path.exists(dir):
175
        raise NameError('Container does not exist')
176
    else:
177
        os.chdir(dir)
178
    f = open(location, 'w')
179
    f.write(data)
180
    f.close()
181
    
182
def __get_object_linkinfo(name):
183
    c = con.execute('select rowid from objects where name=''?''', (name,))
184
    row = c.fetchone()
185
    if row:
186
        return str(row[0])
187
    else:
188
        raise NameError('Object not found')
189

    
190
def __save_linkinfo(name):
191
    id = con.execute('insert into objects(name) values(?)', (name,)).lastrowid
192
    con.commit()
193
    return id
194
    
195
if __name__ == '__main__':
196
    dirname = 'papagian'
197
    #create_container(dirname)
198
    #assert os.path.exists(dirname)
199
    #assert os.path.isdir(dirname)
200
    
201
    #print get_container_meta(dirname)
202
    
203
    #update_object_meta(dirname, 'photos/animals/dog.jpg', {'name':'dog.jpg'})
204
    #update_object_meta(dirname, 'photos/animals/dog.jpg', {'name':'dog.jpg', 'type':'image', 'size':400})
205
    #print get_object_meta(dirname, 'photos/animals/dog.jpg')
206
    
207
    #f = open('dummy.py')
208
    #data  = f.read()
209
    #update_object(dirname, 'photos/animals/dog.jpg', data)
210
    #update_object(dirname, 'photos/animals/cat.jpg', data)
211
    #update_object(dirname, 'photos/animals/thumbs/cat.jpg', data)
212
    #update_object(dirname, 'photos/fruits/banana.jpg', data)
213
    
214
    #print list_objects(dirname, 'photos/animals');
215
    
216
    copy_object(dirname, 'photos/animals/dog.jpg', 'photos/animals/dog2.jpg')
217
    copy_object(dirname, 'photos/animals/dg.jpg', 'photos/animals/dog2.jpg')
218