Skip to content

Instantly share code, notes, and snippets.

@daeken
Created January 9, 2010 08:31
Show Gist options
  • Save daeken/272794 to your computer and use it in GitHub Desktop.
Save daeken/272794 to your computer and use it in GitHub Desktop.
from pylons import request
class FormException(Exception):
def __init__(self, name, description, value):
self.name, self.description, self.value = name, description, value
class FormEmptyException(FormException):
def __str__(self):
return 'Field %r (%s) is mandatory but empty.' % (self.name, self.description)
class FormInvalidException(FormException):
def __str__(self):
return 'Field %r (%s) failed validation. Value: %r' % (self.name, self.description, self.value)
class Param(object):
def validate_any(self, *args, **kwargs):
return True
def __init__(self, description, mandatory=True):
self.description = description
self.mandatory = mandatory
self.validator = self.validate_any
class Form(object):
def __init__(self):
cls = self.__class__
if not hasattr(cls, '__params__'):
cls.__params__ = params = {}
for name, value in ((name, getattr(cls, name)) for name in dir(cls)):
if isinstance(value, str) and name[:2] != '__':
value = Param(value)
elif not isinstance(value, Param):
continue
if hasattr(cls, 'validate_' + name):
validator = getattr(self, 'validate_' + name)
if callable(validator):
value.validator = validator
params[name] = value
else:
params = cls.__params__
for name in params:
setattr(self, name, request.params.get(name, u''))
for name, param in params.items():
value = request.params.get(name, u'')
if param.mandatory and value == u'':
raise FormEmptyException(name, param.description, value)
elif not param.validator(self, param, value):
raise FormInvalidException(name, param.description, value)
from formlib import *
class LoginForm(Form):
email = 'Email'
password = 'Password'
return_to = Param('Return URI', mandatory=False)
def validate_email(self, form, param, value):
return '@' in value
# ...
try:
form = LoginForm()
except FormEmptyException, e:
return '%s required.' % e.description
except FormInvalidException, e:
return '%s is malformed.' % e.description
if User.login(form.email, form.password):
if form.return_to != u'':
redirect(form.return_to)
else:
redirect_to(...)
else:
return 'Login failed.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment