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
| import tornado.ioloop import tornado.web
from wtforms import validators, fields from wtforms import Form from wtforms.fields.core import UnboundField
class MultiDict(dict): def getlist(self, key): return self[key]
def setlist(self, key, value): self[key] = value
class BaseForm(Form): def __init__(self, handler=None, obj=None, prefix='', **kwargs): if handler is None: return formdata = MultiDict() if handler.request.method == 'POST': for name in handler.request.arguments.keys(): formdata.setlist(name, handler.get_arguments(name)) else: for name in handler.request.query_arguments.keys(): formdata.setlist(name, handler.request.query_arguments[name]) Form.__init__(self, formdata, obj=obj, prefix=prefix, **kwargs)
class LoginForm(BaseForm): email = fields.StringField( validators=[validators.Email(), validators.required(), validators.length(min=5, max=64)]) password = fields.PasswordField(validators=[validators.required()])
class MainHandler(tornado.web.RequestHandler, LoginForm): def __getattribute__(self, item): ret = object.__getattribute__(self, item) if isinstance(ret, UnboundField): form = object.__getattribute__(self, 'form') return getattr(form, item).data return ret
def post(self): self.form = LoginForm(self) print(self.email) self.write("Hello, world")
def make_app(): return tornado.web.Application([ (r"/", MainHandler), ])
if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
|