在使用wtforms 的时候,依然需要继承 wtform 针对tornado重写一下里面的一些方法
参考http://lepture.com/work/tornado-ext
from wtforms.ext.i18n.form import Form as wtForm class Form(wtForm): """ Using this Form instead of wtforms.Form Example:: class SigninForm(Form): email = EmailField('email') password = PasswordField('password') class SigninHandler(RequestHandler): def get(self): form = SigninForm(self.request.arguments) """ LANGUAGES = ['zh'] def __init__(self, formdata=None, obj=None, prefix='', **kwargs): super(Form, self).__init__(formdata, obj, prefix, **kwargs) def process(self, formdata=None, obj=None, **kwargs): if formdata is not None and not hasattr(formdata, 'getlist'): formdata = TornadoArgumentsWrapper(formdata) super(Form, self).process(formdata, obj, **kwargs) class TornadoArgumentsWrapper(dict): def __getattr__(self, key): try: return self[key] except KeyError: #raise AttributeError return None def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError: raise AttributeError def getlist(self, key): try: values = [] for v in self[key]: v = to_unicode(v) #if isinstance(v, unicode): v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v) values.append(v) return values except KeyError: #raise AttributeError return []
这里的基类用的是i18n的,目地是为了让wtforms的内制验证错误能本地化
LANGUAGES = ['zh']Form类里面也需要加上这句话,基本报错信息会变成中文的
初始化Form的时候,传入 tornado 的 request.arguments,
像这样
class LoginForm(Form): name = TextField('user', [Required('用户名不能为空'), ]) pwd = PasswordField('pwd', [Required('密码不能为空'), ]) remember = BooleanField('rem')
form = LoginForm(self.request.arguments)之后调用 form.validate() 验证结果就出来了。
取 数据 可以: name = form.name.data
error的话: form.name.error