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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
# Copyright (C) 2011-2012, Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import types
import cPickle as pickle
from os.path import exists
from active_document import env
from active_toolkit import enforce
_LIST_TYPES = (list, tuple, frozenset)
def active_property(property_class=None, *args, **kwargs):
def getter(func, self):
value = self[func.__name__]
return func(self, value)
def decorate_setter(func, attr):
attr.prop.setter = lambda self, value: \
self.set(attr.name, func(self, value))
attr.prop.on_set = func
return attr
def decorate_getter(func):
enforce(func.__name__ != 'guid',
"Active property should not have 'guid' name")
attr = lambda self: getter(func, self)
attr.setter = lambda func: decorate_setter(func, attr)
attr._is_active_property = True
attr.name = func.__name__
attr.prop = (property_class or ActiveProperty)(
attr.name, *args, **kwargs)
attr.prop.on_get = func
return attr
return decorate_getter
class Metadata(dict):
"""Structure to describe the document.
Dictionary derived class that contains `Property` objects.
"""
def __init__(self, cls):
"""
:param cls:
class inherited from `active_document.Document`
"""
self._name = cls.__name__.lower()
slots = {}
prefixes = {}
for attr in [getattr(cls, i) for i in dir(cls)]:
if not hasattr(attr, '_is_active_property'):
continue
prop = attr.prop
if hasattr(prop, 'slot'):
enforce(prop.slot is None or prop.slot not in slots,
'Property %r has a slot already defined for %r in %r',
prop.name, slots.get(prop.slot), self.name)
slots[prop.slot] = prop.name
if hasattr(prop, 'prefix'):
enforce(not prop.prefix or prop.prefix not in prefixes,
'Property %r has a prefix already defined for %r',
prop.name, prefixes.get(prop.prefix))
prefixes[prop.prefix] = prop.name
if prop.setter is not None:
setattr(cls, attr.name, property(attr, prop.setter))
else:
setattr(cls, attr.name, property(attr))
self[prop.name] = prop
@property
def name(self):
"""Document type name."""
return self._name
def __getitem__(self, prop_name):
enforce(prop_name in self, 'There is no %r property in %r',
prop_name, self.name)
return dict.__getitem__(self, prop_name)
class PropertyMeta(dict):
BLOB_SUFFIX = '.blob'
def __init__(self, path_=None, **meta):
if path_:
with file(path_) as f:
meta.update(pickle.load(f))
if exists(path_ + PropertyMeta.BLOB_SUFFIX):
meta['path'] = path_ + PropertyMeta.BLOB_SUFFIX
meta['mtime'] = os.stat(path_).st_mtime
dict.__init__(self, meta)
@classmethod
def is_blob(cls, blob):
return isinstance(blob, (type(None), basestring, cls)) or \
hasattr(blob, 'read')
class Property(object):
"""Bacis class to collect information about document property."""
def __init__(self, name, permissions=env.ACCESS_PUBLIC, typecast=None,
reprcast=None, default=None):
self.setter = None
self.on_get = lambda self, x: x
self.on_set = None
self._name = name
self._permissions = permissions
self._typecast = typecast
self._reprcast = reprcast
self._default = default
@property
def name(self):
"""Property name."""
return self._name
@property
def permissions(self):
"""Specify access to the property.
Value might be ORed composition of `active_document.ACCESS_*`
constants.
"""
return self._permissions
@property
def typecast(self):
"""Cast property value before storing in the system.
Supported values are:
* `None`, string values
* `int`, interger values
* `float`, float values
* `bool`, boolean values repesented by symbols `0` and `1`
* sequence of strings, property value should confirm one of values
from the sequence
"""
return self._typecast
@property
def composite(self):
"""Is property value a list of values."""
is_composite, __ = _is_composite(self.typecast)
return is_composite
@property
def default(self):
"""Default property value or None."""
return self._default
def decode(self, value):
"""Convert property value according to its `typecast`."""
if self.typecast is None:
return value
return _decode(self.typecast, value)
def to_string(self, value):
"""Convert value to list of strings ready to index."""
result = []
if self._reprcast is not None:
value = self._reprcast(value)
for value in (value if type(value) in _LIST_TYPES else [value]):
if type(value) is bool:
value = int(value)
if type(value) is unicode:
value = unicode(value).encode('utf8')
else:
value = str(value)
result.append(value)
return result
def assert_access(self, mode):
"""Is access to the property permitted.
If there are no permissions, function should raise
`active_document.Forbidden` exception.
:param mode:
one of `active_document.ACCESS_*` constants
to specify the access mode
"""
enforce(mode & self.permissions, env.Forbidden,
'%s access is disabled for %r property',
env.ACCESS_NAMES[mode], self.name)
class BrowsableProperty(object):
"""Property that can be listed while browsing documents."""
pass
class StoredProperty(Property, BrowsableProperty):
"""Property that can be saved in persistent storare."""
def __init__(self, name, localized=False, typecast=None, reprcast=None,
**kwargs):
self._localized = localized
if localized:
enforce(typecast is None,
'typecast should be None for localized properties')
enforce(reprcast is None,
'reprcast should be None for localized properties')
typecast = _localized_typecast
reprcast = _localized_reprcast
Property.__init__(self, name, typecast=typecast, reprcast=reprcast,
**kwargs)
@property
def localized(self):
"""Property value will be stored per locale."""
return self._localized
class ActiveProperty(StoredProperty):
"""Property that need to be indexed."""
def __init__(self, name, slot=None, prefix=None, full_text=False,
boolean=False, **kwargs):
enforce(name == 'guid' or slot != 0,
"For %r property, slot '0' is reserved for internal needs",
name)
enforce(name == 'guid' or prefix != env.GUID_PREFIX,
'For %r property, prefix %r is reserved for internal needs',
name, env.GUID_PREFIX)
enforce(slot is not None or prefix or full_text,
'For %r property, either slot, prefix or full_text '
'need to be set',
name)
enforce(slot is None or _is_sloted_prop(kwargs.get('typecast')),
'Slot can be set only for properties for str, int, float, '
'bool types, or, for list of these types')
StoredProperty.__init__(self, name, **kwargs)
self._slot = slot
self._prefix = prefix
self._full_text = full_text
self._boolean = boolean
@property
def slot(self):
"""Xapian document's slot number to add property value to."""
return self._slot
@property
def prefix(self):
"""Xapian serach term prefix, if `None`, property is not a term."""
return self._prefix
@property
def full_text(self):
"""Property takes part in full-text search."""
return self._full_text
@property
def boolean(self):
"""Xapian will use boolean search for this property."""
return self._boolean
class BlobProperty(Property):
"""Binary large objects that need to be fetched alone.
To get access to these properties, use `Document.send()` and
`Document.receive()` functions.
"""
def __init__(self, name, permissions=env.ACCESS_PUBLIC,
mime_type='application/octet-stream', composite=False):
Property.__init__(self, name, permissions=permissions)
self._mime_type = mime_type
self._composite = composite
@property
def mime_type(self):
"""MIME type for BLOB content.
By default, MIME type is application/octet-stream.
"""
return self._mime_type
@property
def composite(self):
"""Property is a list of BLOBs."""
return self._composite
def _is_composite(typecast):
if type(typecast) in _LIST_TYPES:
if typecast:
first = iter(typecast).next()
if type(first) is not type and \
type(first) not in _LIST_TYPES:
return False, True
return True, False
return False, False
def _decode(typecast, value):
enforce(value is not None, ValueError, 'Property value cannot be None')
is_composite, is_enum = _is_composite(typecast)
if is_composite:
enforce(len(typecast) <= 1, ValueError,
'List values should contain values of the same type')
if type(value) not in _LIST_TYPES:
value = (value,)
typecast, = typecast or [str]
value = tuple([_decode(typecast, i) for i in value])
elif is_enum:
enforce(value in typecast, ValueError,
"Value %r is not in '%s' list",
value, ', '.join([str(i) for i in typecast]))
elif isinstance(typecast, types.FunctionType):
value = typecast(value)
elif typecast is str:
if isinstance(value, unicode):
value = value.encode('utf-8')
else:
value = str(value)
elif typecast is int:
value = int(value)
elif typecast is float:
value = float(value)
elif typecast is bool:
value = bool(value)
elif typecast is dict:
value = dict(value)
else:
raise ValueError('Unknown typecast')
return value
def _is_sloted_prop(typecast):
if typecast in [None, int, float, bool, str]:
return True
if type(typecast) in _LIST_TYPES:
if typecast and [i for i in typecast
if type(i) in [None, int, float, bool, str]]:
return True
def _localized_typecast(value):
if isinstance(value, dict):
return value
else:
return {env.DEFAULT_LANG: value}
def _localized_reprcast(value):
if isinstance(value, dict):
return value.values()
else:
return [value]
|