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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
|
===================================
Validation Schema with validate.py
===================================
--------------------------
Using the Validator class
--------------------------
:Authors: `Michael Foord`_, `Nicola Larosa`_, `Mark Andrews`_
:Version: Validate 0.2.0
:Date: 2005/08/25
:Homepage: `Validate Homepage`_
:License: `BSD License`_
:Support: `Mailing List`_
.. _Mailing List: http://lists.sourceforge.net/lists/listinfo/configobj-develop
.. _Michael Foord: fuzzyman@voidspace.org.uk
.. _Nicola Larosa: nico@teknico.net
.. _Mark Andrews: mark@la-la.com
.. _This Document:
.. _Validate Homepage: http://www.voidspace.org.uk/python/validate.html
.. _BSD License: http://www.voidspace.org.uk/documents/BSD-LICENSE.txt
.. contents:: Validate Manual
Introduction
============
Validation is used to check that supplied values conform to a specification.
The value can be supplied as a string, e.g. from a config file. In this case
the check will also *convert* the value to the required type. This allows you
to add validation as a transparent layer to access data stored as strings. The
validation checks that the data is correct *and* converts it to the expected
type.
Checks are also strings, and are easy to write. One generic system can be used
to validate information from different sources, via a single consistent
mechanism.
Checks look like function calls, and map to function calls. They can include
parameters and keyword arguments. These arguments are passed to the relevant
function by the ``Validator`` instance, along with the value being checked.
The syntax for checks also allows for specifying a default value. This default
value can be ``None``, no matter what the type of the check. This can be used
to indicate that a value was missing, and so holds no useful value.
Functions either return a new value, or raise an exception. See `Validator
Exceptions`_ for the low down on the exception classes that ``validate.py``
defines.
Some standard functions are provided, for basic data types; these come built
into every validator. Additional checks are easy to write: they can be provided
when the ``Validator`` is instantiated, or added afterwards.
Validate was primarily written to support ConfigObj_, but was designed to be
applicable to many other situations.
For support and bug reports please use the ConfigObj `Mailing List`_.
.. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html
Downloading
===========
The current version is **0.2.0**, dated 25th August 2005.
You can get obtain validate in the following ways :
Files
-----
* validate.py_ from Voidspace
* configobj.zip from Voidspace - See the homepage of ConfigObj_ for the latest
version and downlaod links.
This contains validate.py and `this document`_. (As well as ConfigObj_ and
the ConfigObj documentation).
* The latest development version can be obtained from the `Subversion Repository`_.
Documentation
-------------
*configobj.zip* contains `this document`_ and full `API Docs`_, generated
automatically by EpyDoc_.
* You can view `this document`_ online as the `Validate Homepage`_.
* You can also browse the `API Docs`_ online.
Pythonutils
-----------
Validate_ is also part of the Pythonutils_ set of modules. This contains
various other useful helper modules, and is required by many of the `Voidspace
Python Projects`_.
.. _configobj.py: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj.py
.. _configobj.zip: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj-4.0.0b4.zip
.. _validate.py: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=validate.py
.. _API Docs: http://www.voidspace.org.uk/python/configobj-api/
.. _Subversion Repository: http://svn.rest2web.python-hosting.com/branches/configobj4/
.. _Sourceforge: http://sourceforge.net/projects/configobj
.. _EpyDoc: http://epydoc.sourceforge.net
.. _pythonutils: http://www.voidspace.org.uk/python/pythonutils.html
.. _Voidspace Python Projects: http://www.voidspace.org.uk/python
.. _validate: http://www.voidspace.org.uk/python/validate.html
The standard functions
======================
The standard functions come built-in to every ``Validator`` instance. They work
with the following basic data types :
* integer
* float
* boolean
* string
* ip_addr
plus lists of these datatypes.
Adding additional checks is done through coding simple functions.
The full set of standard checks are :
:'integer': matches integer values (including negative). Takes optional 'min'
and 'max' arguments : ::
integer()
integer(3, 9) # any value from 3 to 9
integer(min=0) # any positive value
integer(max=9)
:'float': matches float values
Has the same parameters as the integer check.
:'bool': matches boolean values: ``True`` or ``False``.
Acceptable string values for True are : ::
true, on, yes, 1
Acceptable string values for False are : ::
false, off, no, 0
Any other value raises an error.
:'string': matches any string. Takes optional keyword args 'min' and 'max' to
specify min and max length of string.
:'ip_addr': matches an Internet Protocol address, v.4, represented by a
dotted-quad string, i.e. '1.2.3.4'.
:'list': matches any list. Takes optional keyword args 'min', and 'max' to
specify min and max sizes of the list.
:'int_list': Matches a list of integers. Takes the same arguments as list.
:'float_list': Matches a list of floats. Takes the same arguments as list.
:'bool_list': Matches a list of boolean values. Takes the same arguments as
list.
:'string_list': Matches a list of strings. Takes the same arguments as list.
:'ip_addr_list': Matches a list of IP addresses. Takes the same arguments as
list.
:'mixed_list': Matches a list with different types in specific positions.
List size must match the number of arguments.
Each position can be one of : ::
int, str, bool, float, ip_addr
So to specify a list with two strings followed by two integers,
you write the check as : ::
mixed_list(str, str, int, int)
:'pass': matches everything: it never fails and the value is unchanged. It is
also the default if no check is specified.
:'option': matches any from a list of options.
You specify this test with : ::
option('option 1', 'option 2', 'option 3')
The following code will work without you having to specifically add the
functions yourself.
.. raw:: html
{+coloring}
from validate import Validator
#
vtor = Validator()
newval1 = vtor.check(value1, 'integer')
newval2 = vtor.check(value2, 'bool')
# etc ...
{-coloring}
.. note::
Of course, if these checks fail they raise exceptions. So you should wrap
them in ``try...except`` blocks. Better still, use ConfigObj for a higher
level interface.
Using Validator
===============
Using ``Validator`` is very easy. It has one public attribute and one public
method.
Shown below are the different steps in using ``Validator``.
The only additional thing you need to know, is about `Writing check
functions`_.
Instantiate
-----------
.. raw:: html
{+coloring}
from validate import Validator
vtor = Validator()
{-coloring}
or even :
.. raw:: html
{+coloring}
from validate import Validator
#
fdict = {
'check_name1': function1,
'check_name2': function2,
'check_name3': function3,
}
#
vtor = Validator(fdict)
{-coloring}
The second method adds a set of your functions as soon as your validator is
created. They are stored in the ``vtor.functions`` dictionary. The 'key' you
give them in this dictionary is the name you use in your checks (not the
original function name).
Dictionary keys/functions you pass in can override the built-in ones if you
want.
Adding functions
----------------
The code shown above, for adding functions on instantiation, has exactly the
same effect as the following code :
.. raw:: html
{+coloring}
from validate import Validator
#
vtor = Validator()
vtor.functions['check_name1'] = function1
vtor.functions['check_name2'] = function2
vtor.functions['check_name3'] = function3
{-coloring}
``vtor.functions``is just a dictionary that maps names to functions, so we
could also have called ``vtor.functions.update(fdict)``.
Writing the check
-----------------
As we've heard, the checks map to the names in the ``functions`` dictionary.
You've got a full list of `The standard functions`_ and the arguments they
take.
If you're using ``Validator`` from ConfigObj, then your checks will look like
: ::
keyword = int_list(max=6)
but the check part will be identical .
The check method
----------------
If you're not using ``Validator`` from ConfigObj, then you'll need to call the
``check`` method yourself.
If the check fails then it will raise an exception, so you'll want to trap
that. Here's the basic example :
.. raw:: html
{+coloring}
from validate import Validator, ValidateError
#
vtor = Validator()
check = "integer(0, 9)"
value = 3
try:
newvalue = vtor.check(check, value)
except ValidateError:
print 'Check Failed.'
else:
print 'Check passed.'
{-coloring}
.. caution::
Although the value can be a string, if it represents a list it should
already have been turned into a list of strings.
Default Values
~~~~~~~~~~~~~~
Some values may not be available, and you may want to be able to specify a
default as part of the check.
You do this by passing the keyword ``missing=True`` to the ``check`` method, as
well as a ``default=value`` in the check. (Constructing these checks is done
automatically by ConfigObj: you only need to know about the ``default=value``
part) :
.. raw:: html
{+coloring}
check1 = 'integer(default=50)'
check2 = 'option("val 1", "val 2", "val 3", default="val 1")'
assert vtor.check('', check1, missing=True) == 50
assert vtor.check('', check2, missing=True) == "val 1"
{-coloring}
If you pass in ``missing=True`` to the check method, then the actual value is
ignored. If no default is specified in the check, a ``ValidateMissingValue``
exception is raised. If a default is specified then that is passed to the
check instead.
If the check has ``default=None`` (case sensitive) then ``vtor.check`` will
*always* return ``None`` (the object). This makes it easy to tell your program
that this check contains no useful value when missing, i.e. the value is
optional, and may be omitted without harm.
Validator Exceptions
====================
.. note::
If you only use Validator through ConfigObj, it traps these Exceptions for
you. You will still need to know about them for writing your own check
functions.
``vtor.check`` indicates that the check has failed by raising an exception.
The appropriate error should be raised in the check function.
The base error class is ``ValidateError``. All errors (except for ``VdtParamError``)
raised are sub-classes of this.
If an unrecognised check is specified then ``VdtUnknownCheckError`` is
raised.
There are also ``VdtTypeError`` and ``VdtValueError``.
If incorrect parameters are passed to a check function then it will (or should)
raise ``VdtParamError``. As this indicates *programmer* error, rather than an error
in the value, it is a subclass of ``SyntaxError`` instead of ``ValidateError``.
.. note::
This means it *won't* be caught by ConfigObj - but propagated instead.
If the value supplied is the wrong type, then the check should raise
``VdtTypeError``. e.g. the check requires the value to be an integer (or
representation of an integer) and something else was supplied.
If the value supplied is the right type, but an unacceptable value, then the
check should raise ``VdtValueError``. e.g. the check requires the value to
be an integer (or representation of an integer) less than ten and a higher
value was supplied.
Both ``VdtTypeError`` and ``VdtValueError`` are initialised with the
incorrect value. In other words you raise them like this :
.. raw:: html
{+coloring}
raise VdtTypeError(value)
#
raise VdtValueError(value)
{-coloring}
``VdtValueError`` has the following subclasses, which should be raised if
they are more appropriate.
* ``VdtValueTooSmallError``
* ``VdtValueTooBigError``
* ``VdtValueTooShortError``
* ``VdtValueTooLongError``
Writing check functions
=======================
Writing check functions is easy.
The check function will receive the value as its first argument, followed by
any other parameters and keyword arguments.
If the check fails, it should raise a ``VdtTypeError`` or a
``VdtValueError`` (or an appropriate subclass).
All parameters and keyword arguments are *always* passed as strings. (Parsed
from the check string).
The value might be a string (or list of strings) and need
converting to the right type - alternatively it might already be a list of
integers. Our function needs to be able to handle either.
If the check passes then it should return the value (possibly converted to the
right type).
And that's it !
Example
-------
Here is an example function that requires a list of integers. Each integer
must be between 0 and 99.
It takes a single argument specifying the length of the list. (Which allows us
to use the same check in more than one place). If the length can't be converted
to an integer then we need to raise ``VdtParamError``.
Next we check that the value is a list. Anything else should raise a
``VdtTypeError``. The list should also have 'length' entries. If the list
has more or less entries then we will need to raise a
``VdtValueTooShortError`` or a ``VdtValueTooLongError``.
Then we need to check every entry in the list. Each entry should be an integer
between 0 and 99, or a string representation of an integer between 0 and 99.
Any other type is a ``VdtTypeError``, any other value is a
``VdtValueError`` (either too big, or too small).
.. raw:: html
{+coloring}
def special_list(value, length):
"""
Check that the supplied value is a list of integers,
with 'length' entries, and each entry between 0 and 99.
"""
# length is supplied as a string
# we need to convert it to an integer
try:
length = int(length)
except ValueError:
raise VdtParamError('length', length)
#
# Check the supplied value is a list
if not isinstance(value, list):
raise VdtTypeError(value)
#
# check the length of the list is correct
if len(value) > length:
raise VdtValueTooLongError(value)
elif len(value) < length:
raise VdtValueTooShortError(value)
#
# Next, check every member in the list
# converting strings as necessary
out = []
for entry in value:
if not isinstance(entry, (str, unicode, int)):
# a value in the list
# is neither an integer nor a string
raise VdtTypeError(value)
elif isinstance(entry, (str, unicode)):
if not entry.isdigit():
raise VdtTypeError(value)
else:
entry = int(entry)
if entry < 0:
raise VdtValueTooSmallError(value)
elif entry > 99:
raise VdtValueTooBigError(value)
out.append(entry)
#
# if we got this far, all is well
# return the new list
return out
{-coloring}
If you are only using validate from ConfigObj then the error type (*TooBig*,
*TooSmall*, etc) is lost - so you may only want to raise ``VdtValueError``.
.. caution::
If your function raises an exception that isn't a subclass of
``ValidateError``, then ConfigObj won't trap it. This means validation will
fail.
This is why our function starts by checking the type of the value. If we
are passed the wrong type (e.g. an integer rather than a list) we get a
``VdtTypeError`` rather than bombing out when we try to iterate over
the value.
If you are using validate in another circumstance you may want to create your
own subclasses of ``ValidateError``, that convey more specific information.
TODO
====
* A regex check function ?
* A timestamp check function ? (Using the ``parse`` function from ``DateUtil``).
* Allow triple quotes ? (getting a bit heavy for a single regex)
ISSUES
======
.. note::
Please file any bug reports to `Michael Foord`_ or the ConfigObj
`Mailing List`_.
Lists passed as function arguments need additional quotes. Ugly, could do
with fixing this.
If we could pull tuples out of arguments, it would be easier
to specify arguments for 'mixed_lists'.
CHANGELOG
=========
2005/08/18 Version 0.2.0
-----------------------------
Updated by `Michael Foord`_ and `Nicola Larosa`_
Does type conversion as well.
2005/02/01 Version 0.1.0
-----------------------------
Initial version developed by `Michael Foord`_
and `Mark Andrews`_
.. note::
Rendering this document with docutils also needs the
textmacros module and the PySrc CSS stuff. See
http://www.voidspace.org.uk/python/firedrop2/textmacros.shtml
.. raw:: html
<div align="center">
<a href="http://www.python.org">
<img src="images/powered_by_python.jpg" width="602" height="186" border="0" />
</a>
<a href="http://www.opensource.org">
<img src="images/osi-certified-120x100.gif" width="120" height="100" border="0" />
<br /><strong>Certified Open Source</strong>
</a>
<br /><br />
<script type="text/javascript" language="JavaScript">var site="s16atlantibots"</script>
<script type="text/javascript" language="JavaScript1.2" src="http://s16.sitemeter.com/js/counter.js?site=s16atlantibots"></script>
<noscript>
<a href="http://s16.sitemeter.com/stats.asp?site=s16atlantibots">
<img src="http://s16.sitemeter.com/meter.asp?site=s16atlantibots" alt="Site Meter" border=0 />
</a>
</noscript>
</div>
|