forked from ish/schemaish
/
attr.py
361 lines (280 loc) · 8.91 KB
/
attr.py
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
"""
Schema attribute types, also imported into the main package.
"""
__all__ = ['String', 'Integer', 'Float', 'Decimal', 'Date',
'Time', 'Boolean', 'Sequence', 'Tuple', 'Structure',
'DateTime','File', 'Invalid']
import itertools
import validatish
# Internal counter used to ensure the order of a meta structure's attributes is
# maintained.
_meta_order = itertools.count()
_MISSING = object()
class Invalid(Exception):
"""
basic schema validation exception
"""
def __init__(self, error_dict):
Exception.__init__(self,error_dict)
self.error_dict=error_dict
m = []
for k,v in self.error_dict.items():
m.append( 'field "%s" %s'%(k,v.message))
self.message = '\n'.join(m)
def __str__(self):
return self.message
__unicode__ = __str__
class Attribute(object):
"""
Abstract base class for all attribute types in the package.
@ivar title: Title of the attribute.
@ivar description: Optional description.
@ivar validator: Optional FormEncode validator.
"""
title = None
description = None
validator = validatish.Always()
def __init__(self, **k):
"""
Create a new attribute.
@param title: Title of the attribute.
@keyword description: Optional description.
@keyword validator: Optional FormEncode validator.
"""
self._meta_order = _meta_order.next()
title = k.pop('title', _MISSING)
if title is not _MISSING:
self.title = title
description = k.pop('description', _MISSING)
if description is not _MISSING:
self.description = description
validator = k.pop('validator', _MISSING)
if validator is not _MISSING:
self.validator = validator
def validate(self, value):
"""
Validate the value if a validator has been provided.
"""
if not self.validator:
return
try:
self.validator(value)
except validatish.Invalid, e:
raise Invalid({'':e})
def __repr__(self):
attributes = []
if self.title:
attributes.append('title=%s'%repr(self.title))
if self.description:
attributes.append('description=%s'%repr(self.description))
if self.validator:
attributes.append('validator=%s'%repr(self.validator))
return 'schemaish.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
class String(Attribute):
"""
A Python unicode instance.
"""
pass
class Integer(Attribute):
"""
A Python integer.
"""
pass
class Float(Attribute):
"""
A Python float.
"""
pass
class Decimal(Attribute):
"""
A decimal.Decimal instance.
"""
pass
class Date(Attribute):
"""
A datetime.date instance.
"""
pass
class Time(Attribute):
"""
A datetime.time instance.
"""
pass
class DateTime(Attribute):
"""
A datetime.datetime instance.
"""
pass
class Boolean(Attribute):
"""
A Python Boolean instance.
"""
pass
class Sequence(Attribute):
"""
A sequence (Python list) of attributes of a specific type.
@ivar attr: Attribute type of items in the sequence.
"""
attr = None
def __init__(self, attr=None, **k):
"""
Create a new Sequence instance.
@keyword attr: Attribute type of items in the sequence.
"""
super(Sequence, self).__init__(**k)
if attr is not None:
self.attr = attr
def validate(self, value):
"""
Validate all items in the sequence and then validate the Sequence
itself.
"""
error_dict= {}
if value is not None:
for n, item in enumerate(value):
try:
self.attr.validate(item)
except Invalid, e:
for k, v in e.error_dict.items():
if k == '':
error_dict[str(n)] = v
else:
error_dict['%s.%s' % (str(n), k)] = v
try:
super(Sequence, self).validate(value)
except Invalid, e:
error_dict.update(e.error_dict)
if error_dict:
raise Invalid(error_dict)
def __repr__(self):
return 'schemaish.Sequence(%r)'%self.attr
class Tuple(Attribute):
"""
A Python tuple of attributes of specific types.
@ivar attrs: List of Attributes that define the items in the tuple.
"""
attrs = None
def __init__(self, attrs=None, **k):
"""
Create a Tuple instance.
@param attrs: List of Attributes that define the items in the tuple.
"""
super(Tuple, self).__init__(**k)
if attrs is not None:
self.attrs = attrs
def add(self, attr):
"""
Add an attribute to the tuple
@param attr: Attribute type.
"""
if attr is None:
self.attrs = [attr]
else:
self.attrs.append(attr)
def validate(self, value):
"""
Validate the tuple's items and the tuple itself.
"""
if value:
if len(self.attrs) != len(value):
raise Invalid({'':validatish.Invalid("Incorrect size")})
for attr, item in zip(self.attrs, value):
attr.validate(item)
super(Tuple, self).validate(value)
def __repr__(self):
return 'schemaish.Tuple(%r)'%self.attr
class _StructureMeta(type):
def __init__(cls, name, bases, clsattrs):
attrs = []
for (name, value) in clsattrs.items():
if isinstance(value, Attribute):
attrs.append((name, value))
del clsattrs[name]
attrs = [(a[1]._meta_order, a) for a in attrs]
attrs.sort()
attrs = [i[1] for i in attrs]
cls.attrs = attrs
class Structure(Attribute):
"""
Python dict conforming to a fixed structure.
The class can be used to build a structure programmatically or using meta
class syntax. For example the following result in s1 and s2 defining the
same structure:
>>> from schemaish import Structure, String
>>> s1 = Structure()
>>> s1.add("title", String())
>>> s1.add("first", String(title="First Name"))
>>> s1.add("last", String(title="Last Name"))
>>> class Name(Structure):
... title = String()
... first = String(title="First Name")
... last = String(title="Last Name")
...
>>> s2 = Name()
@ivar attrs: List of (name, attribute) tuples each of which defines the
names and type of an attribute of the structure.
"""
__metaclass__ = _StructureMeta
def __init__(self, attrs=None, **k):
"""
Create a new structure.
@params attrs: List of (name, attribute) tuples defining the name and
type of the structure's attributes.
"""
super(Structure, self).__init__(**k)
# If attrs has been passed as an arg then use that as the attrs of the
# structure. Otherwise use the class's attrs, making a copy to ensure
# that any added attrs to the instance do not get appended to te
# class's attrs.
if attrs is not None:
self.attrs = attrs
else:
self.attrs = list(self.attrs)
def add(self, name, attr):
"""
Add a names attribute to the structure.
@param name: Attribute name.
@param attr: Attribute type.
"""
self.attrs.append((name, attr))
def get(self, name):
"""
Get the attribute with the given name.
@param name: Name of the attribute to return.
@raise KeyError: Attribute name could not be found.
"""
for (attr_name, attr) in self.attrs:
if attr_name == name:
return attr
raise KeyError(name)
def validate(self, value):
"""
Validate all items in the sequence and then validate the Sequence
itself.
"""
error_dict = {}
if value is not None:
for (name, attr) in self.attrs:
try:
attr.validate(value.get(name))
except Invalid, e:
for k, v in e.error_dict.items():
if k == '':
error_dict[name] = v
else:
error_dict['%s.%s' % (name, k)] = v
try:
super(Structure, self).validate(value)
except Invalid, e:
error_dict.update(e.error_dict)
if error_dict:
raise Invalid(error_dict)
def __repr__(self):
item = '"%s": %s'
attrstrings = [item%a for a in self.attrs]
return 'schemaish.Structure(%s)'%(', '.join(attrstrings))
class File(Attribute):
"""
A File Object
"""
pass