FormEncode is a validation and form generation package. The validation can be used separately from the form generation. The validation works on compound data structures, with all parts being nestable. It is separate from HTTP or any other input mechanism.
These module API docs are divided into section by category.
These functions are used mostly internally by FormEncode.
Core classes for validation.
Returns whether obj is a validator object or not.
This is raised in response to invalid input. It has several public attributes:
Returns the error as a simple data structure – lists, dictionaries, and strings.
If encode_variables is true, then this will return a flat dictionary, encoded with variable_encode
The base class of most validators. See IValidator for more, and FancyValidator for the more common (and more featureful) class.
Messages
Return a dictionary of all the messages of this validator, and any subvalidators if present. Keys are message names, values may be a message or list of messages. This is really just intended for documentation purposes, to show someone all the messages that a validator or compound validator (like Schemas) can produce.
@@: Should this produce a more structured set of messages, so that messages could be unpacked into a rendered form to see the placement of all the messages? Well, probably so.
alias of NoDefault
Return any validators that this validator contains. This is not useful for functional, except to inspect what values are available. Specifically the .all_messages() method uses this to accumulate all possible messages.
FancyValidator is the (abstract) superclass for various validators and converters. A subclass can validate, convert, or do both. There is no formal distinction made here.
Validators have two important external methods:
These two external methods make use of the following four important internal methods that can be overridden. However, none of these have to be overridden, only the ones that are appropriate for the validator.
You should make sure that all possible validation errors are raised in at least one these four methods, not matter which.
Subclasses can also override the __init__() method if the declarative.Declarative model doesn’t work for this.
Validators should have no internal state besides the values given at instantiation. They should be reusable and reentrant.
All subclasses can take the arguments/instance variables:
These parameters are handled at the level of the external methods .to_python() and .from_python already; if you overwrite one of the internal methods, you usually don’t need to care about them.
Messages
Encode a string in base64, stripping whitespace and removing newlines.
alias of NoDefault
alias of NoDefault
alias of NoDefault
A validation method that doesn’t do anything.
A validation method that doesn’t do anything.
The FormEncode schema is one of the most important parts of using FormEncode, as it lets you organize validators into parts that can be re-used between schemas. Generally, a single schema will represent an entire form, but may inherit other schemas for re-usable validation parts (i.e., maybe multiple forms all requires first and last name).
A schema validates a dictionary of values, applying different validators (be key) to the different values. If allow_extra_fields=True, keys without validators will be allowed; otherwise they will raise Invalid. If filter_extra_fields is set to true, then extra fields are not passed back in the results.
Validators are associated with keys either with a class syntax, or as keyword arguments (class syntax is usually easier). Something like:
class MySchema(Schema):
name = Validators.PlainText()
phone = Validators.PhoneNumber()
These will not be available as actual instance variables, but will be collected in a dictionary. To remove a validator in a subclass that is present in a superclass, set it to None, like:
class MySubSchema(MySchema):
name = None
Note that missing fields are handled at the Schema level. Missing fields can have the ‘missing’ message set to specify the error message, or if that does not exist the schema message ‘missingValue’ is used.
Messages
This validator wraps a simple function that validates the form.
The function looks something like this:
>>> def validate(form_values, state, validator):
... if form_values.get('country', 'US') == 'US':
... if not form_values.get('state'):
... return dict(state='You must enter a state')
... if not form_values.get('country'):
... form_values['country'] = 'US'
This tests that the field ‘state’ must be filled in if the country is US, and defaults that country value to ‘US’. The validator argument is the SimpleFormValidator instance, which you can use to format messages or keep configuration state in if you like (for simple ad hoc validation you are unlikely to need it).
To create a validator from that function, you would do:
>>> from formencode.schema import SimpleFormValidator
>>> validator = SimpleFormValidator(validate)
>>> validator.to_python({'country': 'US', 'state': ''}, None)
Traceback (most recent call last):
...
Invalid: state: You must enter a state
>>> sorted(validator.to_python({'state': 'IL'}, None).items())
[('country', 'US'), ('state', 'IL')]
The validate function can either return a single error message (that applies to the whole form), a dictionary that applies to the fields, None which means the form is valid, or it can raise Invalid.
Note that you may update the value_dict in place, but you cannot return a new value.
Another way to instantiate a validator is like this:
>>> @SimpleFormValidator.decorate()
... def MyValidator(value_dict, state):
... return None # or some more useful validation
After this MyValidator will be a SimpleFormValidator instance (it won’t be your function).
Messages
Validator/Converters for use with FormEncode.
Always Valid, returns True or False based on the value and the existance of the value.
If you want to convert strings like 'true' to booleans, then use StringBool.
Examples:
>>> Bool.to_python(0)
False
>>> Bool.to_python(1)
True
>>> Bool.to_python('')
False
>>> Bool.to_python(None)
False
Messages
Formencode validator to check whether a string is in correct CIDR notation (IP address, or IP address plus /mask).
Examples:
>>> cidr = CIDR()
>>> cidr.to_python('127.0.0.1')
'127.0.0.1'
>>> cidr.to_python('299.0.0.1')
Traceback (most recent call last):
...
Invalid: The octets must be within the range of 0-255 (not '299')
>>> cidr.to_python('192.168.0.1/1')
Traceback (most recent call last):
...
Invalid: The network size (bits) must be within the range of 8-32 (not '1')
>>> cidr.to_python('asdf')
Traceback (most recent call last):
...
Invalid: Please enter a valid IP address (a.b.c.d) or IP network (a.b.c.d/e)
Messages
Checks that credit card numbers are valid (if not real).
You pass in the name of the field that has the credit card type and the field with the credit card number. The credit card type should be one of “visa”, “mastercard”, “amex”, “dinersclub”, “discover”, “jcb”.
You must check the expiration date yourself (there is no relation between CC number/types and expiration dates).
>>> cc = CreditCardValidator()
>>> sorted(cc.to_python({'ccType': 'visa', 'ccNumber': '4111111111111111'}).items())
[('ccNumber', '4111111111111111'), ('ccType', 'visa')]
>>> cc.to_python({'ccType': 'visa', 'ccNumber': '411111111111111'})
Traceback (most recent call last):
...
Invalid: ccNumber: You did not enter a valid number of digits
>>> cc.to_python({'ccType': 'visa', 'ccNumber': '411111111111112'})
Traceback (most recent call last):
...
Invalid: ccNumber: You did not enter a valid number of digits
>>> cc().to_python({})
Traceback (most recent call last):
...
Invalid: The field ccType is missing
Messages
Checks that credit card expiration date is valid relative to the current date.
You pass in the name of the field that has the credit card expiration month and the field with the credit card expiration year.
>>> ed = CreditCardExpires()
>>> sorted(ed.to_python({'ccExpiresMonth': '11', 'ccExpiresYear': '2250'}).items())
[('ccExpiresMonth', '11'), ('ccExpiresYear', '2250')]
>>> ed.to_python({'ccExpiresMonth': '10', 'ccExpiresYear': '2005'})
Traceback (most recent call last):
...
Invalid: ccExpiresMonth: Invalid Expiration Date<br>
ccExpiresYear: Invalid Expiration Date
Messages
Checks that credit card security code has the correct number of digits for the given credit card type.
You pass in the name of the field that has the credit card type and the field with the credit card security code.
>>> code = CreditCardSecurityCode()
>>> sorted(code.to_python({'ccType': 'visa', 'ccCode': '111'}).items())
[('ccCode', '111'), ('ccType', 'visa')]
>>> code.to_python({'ccType': 'visa', 'ccCode': '1111'})
Traceback (most recent call last):
...
Invalid: ccCode: Invalid credit card security code length
Messages
Validates and converts a string date, like mm/yy, dd/mm/yy, dd-mm-yy, etc. Using month_style you can support 'mm/dd/yyyy' or 'dd/mm/yyyy'. Only these two general styles are supported.
Accepts English month names, also abbreviated. Returns value as a datetime object (you can get mx.DateTime objects if you use datetime_module='mxDateTime'). Two year dates are assumed to be within 1950-2020, with dates from 21-49 being ambiguous and signaling an error.
Use accept_day=False if you just want a month/year (like for a credit card expiration date).
>>> d = DateConverter()
>>> d.to_python('12/3/09')
datetime.date(2009, 12, 3)
>>> d.to_python('12/3/2009')
datetime.date(2009, 12, 3)
>>> d.to_python('2/30/04')
Traceback (most recent call last):
...
Invalid: That month only has 29 days
>>> d.to_python('13/2/05')
Traceback (most recent call last):
...
Invalid: Please enter a month from 1 to 12
>>> d.to_python('1/1/200')
Traceback (most recent call last):
...
Invalid: Please enter a four-digit year after 1899
If you change month_style you can get European-style dates:
>>> d = DateConverter(month_style='dd/mm/yyyy')
>>> date = d.to_python('12/3/09')
>>> date
datetime.date(2009, 3, 12)
>>> d.from_python(date)
'12/03/2009'
Messages
Validates that a date is within the given range. Be sure to call DateConverter first if you aren’t expecting mxDateTime input.
earliest_date and latest_date may be functions; if so, they will be called each time before validating.
after_now means a time after the current timestamp; note that just a few milliseconds before now is invalid! today_or_after is more permissive, and ignores hours and minutes.
Examples:
>>> from datetime import datetime, timedelta
>>> d = DateValidator(earliest_date=datetime(2003, 1, 1))
>>> d.to_python(datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> d.to_python(datetime(2002, 1, 1))
Traceback (most recent call last):
...
Invalid: Date must be after Wednesday, 01 January 2003
>>> d.to_python(datetime(2003, 1, 1))
datetime.datetime(2003, 1, 1, 0, 0)
>>> d = DateValidator(after_now=True)
>>> now = datetime.now()
>>> d.to_python(now+timedelta(seconds=5)) == now+timedelta(seconds=5)
True
>>> d.to_python(now-timedelta(days=1))
Traceback (most recent call last):
...
Invalid: The date must be sometime in the future
>>> d.to_python(now+timedelta(days=1)) > now
True
>>> d = DateValidator(today_or_after=True)
>>> d.to_python(now) == now
True
Messages
Converts values based on a dictionary which has values as keys for the resultant values.
If allowNull is passed, it will not balk if a false value (e.g., ‘’ or None) is given (it will return None in these cases).
to_python takes keys and gives values, from_python takes values and gives keys.
If you give hideDict=True, then the contents of the dictionary will not show up in error messages.
Examples:
>>> dc = DictConverter({1: 'one', 2: 'two'})
>>> dc.to_python(1)
'one'
>>> dc.from_python('one')
1
>>> dc.to_python(3)
Traceback (most recent call last):
....
Invalid: Enter a value from: 1; 2
>>> dc2 = dc(hideDict=True)
>>> dc2.hideDict
True
>>> dc2.dict
{1: 'one', 2: 'two'}
>>> dc2.to_python(3)
Traceback (most recent call last):
....
Invalid: Choose something
>>> dc.from_python('three')
Traceback (most recent call last):
....
Invalid: Nothing in my dictionary goes by the value 'three'. Choose one of: 'one'; 'two'
Messages
Validate an email address.
If you pass resolve_domain=True, then it will try to resolve the domain name to make sure it’s valid. This takes longer, of course. You must have the pyDNS modules installed to look up DNS (MX and A) records.
>>> e = Email()
>>> e.to_python(' test@foo.com ')
'test@foo.com'
>>> e.to_python('test')
Traceback (most recent call last):
...
Invalid: An email address must contain a single @
>>> e.to_python('test@foobar')
Traceback (most recent call last):
...
Invalid: The domain portion of the email address is invalid (the portion after the @: foobar)
>>> e.to_python('test@foobar.com.5')
Traceback (most recent call last):
...
Invalid: The domain portion of the email address is invalid (the portion after the @: foobar.com.5)
>>> e.to_python('test@foo..bar.com')
Traceback (most recent call last):
...
Invalid: The domain portion of the email address is invalid (the portion after the @: foo..bar.com)
>>> e.to_python('test@.foo.bar.com')
Traceback (most recent call last):
...
Invalid: The domain portion of the email address is invalid (the portion after the @: .foo.bar.com)
>>> e.to_python('nobody@xn--m7r7ml7t24h.com')
'nobody@xn--m7r7ml7t24h.com'
>>> e.to_python('o*reilly@test.com')
'o*reilly@test.com'
>>> e = Email(resolve_domain=True)
>>> e.resolve_domain
True
>>> e.to_python('doesnotexist@colorstudy.com')
'doesnotexist@colorstudy.com'
>>> e.to_python('test@nyu.edu')
'test@nyu.edu'
>>> # NOTE: If you do not have PyDNS installed this example won't work:
>>> e.to_python('test@thisdomaindoesnotexistithinkforsure.com')
Traceback (most recent call last):
...
Invalid: The domain of the email address does not exist (the portion after the @: thisdomaindoesnotexistithinkforsure.com)
>>> e.to_python(u'test@google.com')
u'test@google.com'
>>> e = Email(not_empty=False)
>>> e.to_python('')
Messages
Invalid unless the value is empty. Use cleverly, if at all.
Examples:
>>> Empty.to_python(0)
Traceback (most recent call last):
...
Invalid: You cannot enter a value here
Messages
Tests that the given fields match, i.e., are identical. Useful for password+confirmation fields. Pass the list of field names in as field_names.
>>> f = FieldsMatch('pass', 'conf')
>>> sorted(f.to_python({'pass': 'xx', 'conf': 'xx'}).items())
[('conf', 'xx'), ('pass', 'xx')]
>>> f.to_python({'pass': 'xx', 'conf': 'yy'})
Traceback (most recent call last):
...
Invalid: conf: Fields do not match
Messages
Handles cgi.FieldStorage instances that are file uploads.
This doesn’t do any conversion, but it can detect empty upload fields (which appear like normal fields, but have no filename when no upload was given).
Messages
Takes two inputs (a dictionary with keys static and upload) and converts them into one value on the Python side (a dictionary with filename and content keys). The upload takes priority over the static value. The filename may be None if it can’t be discovered.
Handles uploads of both text and cgi.FieldStorage upload values.
This is basically for use when you have an upload field, and you want to keep the upload around even if the rest of the form submission fails. When converting back to the form submission, there may be extra values 'original_filename' and 'original_content', which may want to use in your form to show the user you still have their content around.
To use this, make sure you are using variabledecode, then use something like:
<input type="file" name="myfield.upload">
<input type="hidden" name="myfield.static">
Then in your scheme:
class MyScheme(Scheme):
myfield = FileUploadKeeper()
Note that big file uploads mean big hidden fields, and lots of bytes passed back and forth in the case of an error.
Messages
A FormValidator is something that can be chained with a Schema.
Unlike normal chaining the FormValidator can validate forms that aren’t entirely valid.
The important method is .validate(), of course. It gets passed a dictionary of the (processed) values from the form. If you have .validate_partial_form set to True, then it will get the incomplete values as well – check with the “in” operator if the form was able to process any particular field.
Anyway, .validate() should return a string or a dictionary. If a string, it’s an error message that applies to the whole form. If not, then it should be a dictionary of fieldName: errorMessage. The special key “form” is the error message for the form as a whole (i.e., a string is equivalent to {“form”: string}).
Returns None on no errors.
Messages
Converts a index (which may be a string like ‘2’) to the value in the given list.
Examples:
>>> index = IndexListConverter(['zero', 'one', 'two'])
>>> index.to_python(0)
'zero'
>>> index.from_python('zero')
0
>>> index.to_python('1')
'one'
>>> index.to_python(5)
Traceback (most recent call last):
Invalid: Index out of range
>>> index(not_empty=True).to_python(None)
Traceback (most recent call last):
Invalid: Please enter a value
>>> index.from_python('five')
Traceback (most recent call last):
Invalid: Item 'five' was not found in the list
Messages
Convert a value to an integer.
Example:
>>> Int.to_python('10') 10 >>> Int.to_python('ten') Traceback (most recent call last): ... Invalid: Please enter an integer value >>> Int(min=5).to_python('6') 6 >>> Int(max=10).to_python('11') Traceback (most recent call last): ... Invalid: Please enter a number that is 10 or smaller
Messages
Formencode validator to check whether a string is a correct hardware (MAC) address.
Examples:
>>> mac = MACAddress()
>>> mac.to_python('aa:bb:cc:dd:ee:ff')
'aabbccddeeff'
>>> mac.to_python('aa:bb:cc:dd:ee:ff:e')
Traceback (most recent call last):
...
Invalid: A MAC address must contain 12 digits and A-F; the value you gave has 13 characters
>>> mac.to_python('aa:bb:cc:dd:ee:fx')
Traceback (most recent call last):
...
Invalid: MAC addresses may only contain 0-9 and A-F (and optionally :), not 'x'
>>> MACAddress(add_colons=True).to_python('aabbccddeeff')
'aa:bb:cc:dd:ee:ff'
Messages
Invalid if the value is longer than maxLength. Uses len(), so it can work for strings, lists, or anything with length.
Examples:
>>> max5 = MaxLength(5)
>>> max5.to_python('12345')
'12345'
>>> max5.from_python('12345')
'12345'
>>> max5.to_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5(accept_python=False).from_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python([1, 2, 3])
[1, 2, 3]
>>> max5.to_python([1, 2, 3, 4, 5, 6])
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
Messages
Invalid if the value is shorter than minlength. Uses len(), so it can work for strings, lists, or anything with length. Note that you must use not_empty=True if you don’t want to accept empty values – empty values are not tested for length.
Examples:
>>> min5 = MinLength(5)
>>> min5.to_python('12345')
'12345'
>>> min5.from_python('12345')
'12345'
>>> min5.to_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5(accept_python=False).from_python('1234')
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> min5.to_python([1, 2, 3])
Traceback (most recent call last):
...
Invalid: Enter a value at least 5 characters long
>>> min5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
Messages
Convert a value to a float or integer.
Tries to convert it to an integer if no information is lost.
Example:
>>> Number.to_python('10') 10 >>> Number.to_python('10.5') 10.5 >>> Number.to_python('ten') Traceback (most recent call last): ... Invalid: Please enter a number >>> Number(min=5).to_python('6.5') 6.5 >>> Number(max=10.5).to_python('11.5') Traceback (most recent call last): ... Invalid: Please enter a number that is 10.5 or smaller
Messages
Invalid if value is empty (empty string, empty list, etc).
Generally for objects that Python considers false, except zero which is not considered invalid.
Examples:
>>> ne = NotEmpty(messages=dict(empty='enter something'))
>>> ne.to_python('')
Traceback (most recent call last):
...
Invalid: enter something
>>> ne.to_python(0)
0
Messages
Tests that the value is one of the members of a given list.
If testValueList=True, then if the input value is a list or tuple, all the members of the sequence will be checked (i.e., the input must be a subset of the allowed values).
Use hideList=True to keep the list of valid values out of the error message in exceptions.
Examples:
>>> oneof = OneOf([1, 2, 3])
>>> oneof.to_python(1)
1
>>> oneof.to_python(4)
Traceback (most recent call last):
...
Invalid: Value must be one of: 1; 2; 3 (not 4)
>>> oneof(testValueList=True).to_python([2, 3, [1, 2, 3]])
[2, 3, [1, 2, 3]]
>>> oneof.to_python([2, 3, [1, 2, 3]])
Traceback (most recent call last):
...
Invalid: Value must be one of: 1; 2; 3 (not [2, 3, [1, 2, 3]])
Messages
Test that the field contains only letters, numbers, underscore, and the hyphen. Subclasses Regex.
Examples:
>>> PlainText.to_python('_this9_')
'_this9_'
>>> PlainText.from_python(' this ')
' this '
>>> PlainText(accept_python=False).from_python(' this ')
Traceback (most recent call last):
...
Invalid: Enter only letters, numbers, or _ (underscore)
>>> PlainText(strip=True).to_python(' this ')
'this'
>>> PlainText(strip=True).from_python(' this ')
'this'
Messages
Invalid if the value doesn’t match the regular expression regex.
The regular expression can be a compiled re object, or a string which will be compiled for you.
Use strip=True if you want to strip the value before validation, and as a form of conversion (often useful).
Examples:
>>> cap = Regex(r'^[A-Z]+$')
>>> cap.to_python('ABC')
'ABC'
Note that .from_python() calls (in general) do not validate the input:
>>> cap.from_python('abc')
'abc'
>>> cap(accept_python=False).from_python('abc')
Traceback (most recent call last):
...
Invalid: The input is not valid
>>> cap.to_python(1)
Traceback (most recent call last):
...
Invalid: The input must be a string (not a <type 'int'>: 1)
>>> Regex(r'^[A-Z]+$', strip=True).to_python(' ABC ')
'ABC'
>>> Regex(r'this', regexOps=('I',)).to_python('THIS')
'THIS'
Messages
Require one field based on another field being present or missing.
This validator is applied to a form, not an individual field (usually using a Schema’s pre_validators or chained_validators) and is available under both names RequireIfMissing and RequireIfPresent.
If you provide a missing value (a string key name) then if that field is missing the field must be entered. This gives you an either/or situation.
If you provide a present value (another string key name) then if that field is present, the required field must also be present.
>>> from formencode import validators
>>> v = validators.RequireIfPresent('phone_type', present='phone')
>>> v.to_python(dict(phone_type='', phone='510 420 4577'))
Traceback (most recent call last):
...
Invalid: You must give a value for phone_type
>>> v.to_python(dict(phone=''))
{'phone': ''}
Note that if you have a validator on the optionally-required field, you should probably use if_missing=None. This way you won’t get an error from the Schema about a missing value. For example:
class PhoneInput(Schema):
phone = PhoneNumber()
phone_type = String(if_missing=None)
chained_validators = [RequireIfPresent('phone_type', present='phone')]
Messages
This is for when you think you may return multiple values for a certain field.
This way the result will always be a list, even if there’s only one result. It’s equivalent to ForEach(convert_to_list=True).
If you give use_set=True, then it will return an actual set object.
>>> Set.to_python(None)
[]
>>> Set.to_python('this')
['this']
>>> Set.to_python(('this', 'that'))
['this', 'that']
>>> s = Set(use_set=True)
>>> s.to_python(None)
set([])
>>> s.to_python('this')
set(['this'])
>>> s.to_python(('this',))
set(['this'])
Messages
Encodes a string into a signed string, and base64 encodes both the signature string and a random nonce.
It is up to you to provide a secret, and to keep the secret handy and consistent.
Messages
Converts things to string, but treats empty things as the empty string.
Also takes a max and min argument, and the string length must fall in that range.
Also you may give an encoding argument, which will encode any unicode that is found. Lists and tuples are joined with list_joiner (default ', ') in from_python.
>>> String(min=2).to_python('a')
Traceback (most recent call last):
...
Invalid: Enter a value 2 characters long or more
>>> String(max=10).to_python('xxxxxxxxxxx')
Traceback (most recent call last):
...
Invalid: Enter a value not more than 10 characters long
>>> String().from_python(None)
''
>>> String().from_python([])
''
>>> String().to_python(None)
''
>>> String(min=3).to_python(None)
Traceback (most recent call last):
...
Invalid: Please enter a value
>>> String(min=1).to_python('')
Traceback (most recent call last):
...
Invalid: Please enter a value
Messages
Converts a string to a boolean.
Values like ‘true’ and ‘false’ are considered True and False, respectively; anything in true_values is true, anything in false_values is false, case-insensitive). The first item of those lists is considered the preferred form.
>>> s = StringBool()
>>> s.to_python('yes'), s.to_python('no')
(True, False)
>>> s.to_python(1), s.to_python('N')
(True, False)
>>> s.to_python('ye')
Traceback (most recent call last):
...
Invalid: Value should be 'true' or 'false'
Messages
Take a field from a dictionary, removing the key from the dictionary.
name is the key. The field value and a new copy of the dictionary with that field removed are returned.
>>> StripField('test').to_python({'a': 1, 'test': 2})
(2, {'a': 1})
>>> StripField('test').to_python({})
Traceback (most recent call last):
...
Invalid: The name 'test' is missing
Messages
Converts times in the format HH:MM:SSampm to (h, m, s). Seconds are optional.
For ampm, set use_ampm = True. For seconds, use_seconds = True. Use ‘optional’ for either of these to make them optional.
Examples:
>>> tim = TimeConverter()
>>> tim.to_python('8:30')
(8, 30)
>>> tim.to_python('20:30')
(20, 30)
>>> tim.to_python('30:00')
Traceback (most recent call last):
...
Invalid: You must enter an hour in the range 0-23
>>> tim.to_python('13:00pm')
Traceback (most recent call last):
...
Invalid: You must enter an hour in the range 1-12
>>> tim.to_python('12:-1')
Traceback (most recent call last):
...
Invalid: You must enter a minute in the range 0-59
>>> tim.to_python('12:02pm')
(12, 2)
>>> tim.to_python('12:02am')
(0, 2)
>>> tim.to_python('1:00PM')
(13, 0)
>>> tim.from_python((13, 0))
'13:00:00'
>>> tim2 = tim(use_ampm=True, use_seconds=False)
>>> tim2.from_python((13, 0))
'1:00pm'
>>> tim2.from_python((0, 0))
'12:00am'
>>> tim2.from_python((12, 0))
'12:00pm'
Examples with datetime.time:
>>> v = TimeConverter(use_datetime=True)
>>> a = v.to_python('18:00')
>>> a
datetime.time(18, 0)
>>> b = v.to_python('30:00')
Traceback (most recent call last):
...
Invalid: You must enter an hour in the range 0-23
>>> v2 = TimeConverter(prefer_ampm=True, use_datetime=True)
>>> v2.from_python(a)
'6:00:00pm'
>>> v3 = TimeConverter(prefer_ampm=True,
... use_seconds=False, use_datetime=True)
>>> a = v3.to_python('18:00')
>>> a
datetime.time(18, 0)
>>> v3.from_python(a)
'6:00pm'
>>> a = v3.to_python('18:00:00')
Traceback (most recent call last):
...
Invalid: You may not enter seconds
Messages
Converts things to unicode string, this is a specialization of the String class.
In addition to the String arguments, an encoding argument is also accepted. By default the encoding will be utf-8. You can overwrite this using the encoding parameter. You can also set inputEncoding and outputEncoding differently. An inputEncoding of None means “do not decode”, an outputEncoding of None means “do not encode”.
All converted strings are returned as Unicode strings.
>>> UnicodeString().to_python(None)
u''
>>> UnicodeString().to_python([])
u''
>>> UnicodeString(encoding='utf-7').to_python('Ni Ni Ni')
u'Ni Ni Ni'
Messages
Validate a URL, either http://... or https://. If check_exists is true, then we’ll actually make a request for the page.
If add_http is true, then if no scheme is present we’ll add http://
>>> u = URL(add_http=True)
>>> u.to_python('foo.com')
'http://foo.com'
>>> u.to_python('http://hahaha.ha/bar.html')
'http://hahaha.ha/bar.html'
>>> u.to_python('http://xn--m7r7ml7t24h.com')
'http://xn--m7r7ml7t24h.com'
>>> u.to_python('http://xn--c1aay4a.xn--p1ai')
'http://xn--c1aay4a.xn--p1ai'
>>> u.to_python('http://foo.com/test?bar=baz&fleem=morx')
'http://foo.com/test?bar=baz&fleem=morx'
>>> u.to_python('http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest')
'http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest'
>>> u.to_python('http://foo.com:8000/test.html')
'http://foo.com:8000/test.html'
>>> u.to_python('http://foo.com/something\nelse')
Traceback (most recent call last):
...
Invalid: That is not a valid URL
>>> u.to_python('https://test.com')
'https://test.com'
>>> u.to_python('http://test')
Traceback (most recent call last):
...
Invalid: You must provide a full domain name (like test.com)
>>> u.to_python('http://test..com')
Traceback (most recent call last):
...
Invalid: That is not a valid URL
>>> u = URL(add_http=False, check_exists=True)
>>> u.to_python('http://google.com')
'http://google.com'
>>> u.to_python('google.com')
Traceback (most recent call last):
...
Invalid: You must start your URL with http://, https://, etc
>>> u.to_python('http://www.formencode.org/does/not/exist/page.html')
Traceback (most recent call last):
...
Invalid: The server responded that the page could not be found
>>> u.to_python('http://this.domain.does.not.exist.example.org/test.html')
...
Traceback (most recent call last):
...
Invalid: An error occured when trying to connect to the server: ...
If you want to allow addresses without a TLD (e.g., localhost) you can do:
>>> URL(require_tld=False).to_python('http://localhost')
'http://localhost'
By default, internationalized domain names (IDNA) in Unicode will be accepted and encoded to ASCII using Punycode (as described in RFC 3490). You may set allow_idna to False to change this behavior:
>>> URL(allow_idna=True).to_python(
... u'http://\u0433\u0443\u0433\u043b.\u0440\u0444')
'http://xn--c1aay4a.xn--p1ai'
>>> URL(allow_idna=True, add_http=True).to_python(
... u'\u0433\u0443\u0433\u043b.\u0440\u0444')
'http://xn--c1aay4a.xn--p1ai'
>>> URL(allow_idna=False).to_python(
... u'http://\u0433\u0443\u0433\u043b.\u0440\u0444')
Traceback (most recent call last):
...
Invalid: That is not a valid URL
Messages
Confirms that the input/output is of the proper type.
Uses the parameters:
Examples:
>>> cint = ConfirmType(subclass=int)
>>> cint.to_python(True)
True
>>> cint.to_python('1')
Traceback (most recent call last):
...
Invalid: '1' is not a subclass of <type 'int'>
>>> cintfloat = ConfirmType(subclass=(float, int))
>>> cintfloat.to_python(1.0), cintfloat.from_python(1.0)
(1.0, 1.0)
>>> cintfloat.to_python(1), cintfloat.from_python(1)
(1, 1)
>>> cintfloat.to_python(None)
Traceback (most recent call last):
...
Invalid: None is not a subclass of one of the types <type 'float'>, <type 'int'>
>>> cint2 = ConfirmType(type=int)
>>> cint2(accept_python=False).from_python(True)
Traceback (most recent call last):
...
Invalid: True must be of the type <type 'int'>
Messages
Used to convert functions to validator/converters.
You can give a simple function for to_python, from_python, validate_python or validate_other. If that function raises an exception, the value is considered invalid. Whatever value the function returns is considered the converted value.
Unlike validators, the state argument is not used. Functions like int can be used here, that take a single argument.
Note that as Wrapper will generate a FancyValidator, empty values (those who pass FancyValidator.is_empty) will return None. To override this behavior you can use Wrapper(empty_value=callable). For example passing Wrapper(empty_value=lambda val: val) will return the value itself when is considered empty.
Examples:
>>> def downcase(v):
... return v.lower()
>>> wrap = Wrapper(to_python=downcase)
>>> wrap.to_python('This')
'this'
>>> wrap.from_python('This')
'This'
>>> wrap.to_python('') is None
True
>>> wrap2 = Wrapper(from_python=downcase, empty_value=lambda val: val)
>>> wrap2.from_python('This')
'this'
>>> wrap2.to_python('')
''
>>> wrap2.from_python(1)
Traceback (most recent call last):
...
Invalid: 'int' object has no attribute 'lower'
>>> wrap3 = Wrapper(validate_python=int)
>>> wrap3.to_python('1')
'1'
>>> wrap3.to_python('a')
Traceback (most recent call last):
...
Invalid: invalid literal for int()...
Messages
This converter converts everything to the same thing.
I.e., you pass in the constant value when initializing, then all values get converted to that constant value.
This is only really useful for funny situations, like:
# Any evaluates sub validators in reverse order for to_python
fromEmailValidator = Any(
Constant('unknown@localhost'),
Email())
In this case, the if the email is not valid 'unknown@localhost' will be used instead. Of course, you could use if_invalid instead.
Examples:
>>> Constant('X').to_python('y')
'X'
Messages
Validators for applying validations in sequence.
This class is like an ‘or’ operator for validators. The first validator/converter in the order of evaluation that validates the value will be used.
The order of evaluation differs depending on if you are validating to python or from python as follows:
The validators are evaluated right to left when validating to python.
The validators are evaluated left to right when validating from python.
This class is like an ‘and’ operator for validators. All validators must work, and the results are passed in turn through all validators for conversion in the order of evaluation. All is the same as Pipe but operates in the reverse order.
The order of evaluation differs depending on if you are validating to python or from python as follows:
The validators are evaluated right to left when validating to python.
The validators are evaluated left to right when validating from python.
Pipe is more intuitive when predominatenly validating to python.
Examples:
>>> from formencode.validators import DictConverter
>>> av = All(validators=[DictConverter({2: 1}), DictConverter({3: 2}), DictConverter({4: 3})])
>>> av.to_python(4)
1
>>> av.from_python(1)
4
Validator for repeating items.
Use this to apply a validator/converter to each item in a list.
For instance:
ForEach(AsInt(), InList([1, 2, 3]))
Will take a list of values and try to convert each of them to an integer, and then check if each integer is 1, 2, or 3. Using multiple arguments is equivalent to:
ForEach(All(AsInt(), InList([1, 2, 3])))
Use convert_to_list=True if you want to force the input to be a list. This will turn non-lists into one-element lists, and None into the empty list. This tries to detect sequences by iterating over them (except strings, which aren’t considered sequences).
ForEach will try to convert the entire list, even if errors are encountered. If errors are encountered, they will be collected and a single Invalid exception will be raised at the end (with error_list set).
If the incoming value is a set, then we return a set.
Parser for HTML forms, that fills in defaults and errors. See render.
Render the form (which should be a string) given the defaults and errors. Defaults are the values that go in the input fields (overwriting any values that are there) and errors are displayed inline in the form (and also effect input classes). Returns the rendered string.
If auto_insert_errors is true (the default) then any errors for which <form:error> tags can’t be found will be put just above the associated input field, or at the top of the form if no field can be found.
If use_all_keys is true, if there are any extra fields from defaults or errors that couldn’t be used in the form it will be an error.
error_formatters is a dictionary of formatter names to one-argument functions that format an error into HTML. Some default formatters are provided if you don’t provide this.
error_class is the class added to input fields when there is an error for that field.
add_attributes is a dictionary of field names to a dictionary of attribute name/values. If the name starts with + then the value will be appended to any existing attribute (e.g., {'+class': ' important'}).
auto_error_formatter is used to create the HTML that goes above the fields. By default it wraps the error message in a span and adds a <br>.
If text_as_default is true (default false) then <input type="unknown"> will be treated as text inputs.
If checkbox_checked_if_present is true (default false) then <input type="checkbox"> will be set to checked if any corresponding key is found in the defaults dictionary, even a value that evaluates to False (like an empty string). This can be used to support pre-filling of checkboxes that do not have a value attribute, since browsers typically will only send the name of the checkbox in the form submission if the checkbox is checked, so simply the presence of the key would mean the box should be checked.
listener can be an object that watches fields pass; the only one currently is in htmlfill_schemabuilder.SchemaBuilder
encoding specifies an encoding to assume when mixing str and unicode text in the template.
prefix_error specifies if the HTML created by auto_error_formatter is put before the input control (default) or after the control.
force_defaults specifies if a field default is not given in the defaults dictionary then the control associated with the field should be set as an unsuccessful control. So checkboxes will be cleared, radio and select controls will have no value selected, and textareas will be emptied. This defaults to True, which is appropriate the defaults are the result of a form submission.
Formatter that escapes the error, wraps the error in a span with class error-message, and adds a <br>
Formatter that does nothing, no escaping HTML, nothin’
Formatter that escapes HTML, no more.
Formatter that escapes HTML, and translates newlines to <br>
Fills HTML with default values, as in a form.
Examples:
>>> defaults = dict(name='Bob Jones',
... occupation='Crazy Cultist',
... address='14 W. Canal\nNew Guinea',
... living='no',
... nice_guy=0)
>>> parser = FillingParser(defaults)
>>> parser.feed('''<input type="text" name="name" value="fill">
... <select name="occupation"> <option value="">Default</option>
... <option value="Crazy Cultist">Crazy cultist</option> </select>
... <textarea cols="20" style="width: 100%" name="address">
... An address</textarea>
... <input type="radio" name="living" value="yes">
... <input type="radio" name="living" value="no">
... <input type="checkbox" name="nice_guy" checked="checked">''')
>>> parser.close()
>>> print parser.text()
<input type="text" name="name" value="Bob Jones">
<select name="occupation">
<option value="">Default</option>
<option value="Crazy Cultist" selected="selected">Crazy cultist</option>
</select>
<textarea cols="20" style="width: 100%" name="address">14 W. Canal
New Guinea</textarea>
<input type="radio" name="living" value="yes">
<input type="radio" name="living" value="no" checked="checked">
<input type="checkbox" name="nice_guy">