Tornado Web 开发 框架搭建 (3)

Form验证

在使用wtforms 的时候,依然需要继承 wtform 针对tornado重写一下里面的一些方法

参考http://lepture.com/work/tornado-ext

 

?

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
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的内制验证错误能本地化


?

1
LANGUAGES = [ 'zh' ]

Form类里面也需要加上这句话,基本报错信息会变成中文的


初始化Form的时候,传入 tornado 的 request.arguments,

像这样


?

1
2
3
4
class LoginForm(Form):
     name = TextField( 'user' , [Required( '用户名不能为空' ), ])
     pwd = PasswordField( 'pwd' , [Required( '密码不能为空' ), ])
     remember = BooleanField( 'rem' )


?

1
form = LoginForm( self .request.arguments)

之后调用 form.validate() 验证结果就出来了。

取 数据 可以: name = form.name.data

error的话: form.name.error


你可能感兴趣的:(Tornado Web 开发 框架搭建 (3))