我没有发现用 WTForms 表单替换 Tornado 模板中包含的基本 html 表单,并没有像我希望的那样直观。
这是一个非常简单的表单示例wtforms-tornado
:
模板:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Simple Form</title>
<meta name="description" content="Submit Track to Infinite Glitch">
</head>
<body>
<p><h1>Submit Info</h1></p>
<form enctype="multipart/form-data" action="/simple" method="post">
{{ form.name }}<br/>
{{ form.email }}<br/>
{{ form.message }}<br/>
<input type="submit"/>
</form>
</body>
</html>
应用代码:
import wtforms
from wtforms_tornado import Form
class EasyForm(Form):
name = wtforms.TextField('name', validators=[wtforms.validators.DataRequired()], default=u'test')
email = wtforms.TextField('email', validators=[wtforms.validators.Email(), wtforms.validators.DataRequired()])
message = wtforms.TextAreaField('message', validators=[wtforms.validators.DataRequired()])
class SimpleForm(tornado.web.RequestHandler):
def get(self):
form = EasyForm()
self.write(templates.load("simpleform.html").generate(compiled=compiled, form=form))
def post(self):
form = EasyForm(self.request.arguments)
details = '';
if form.validate():
for f in self.request.arguments:
details += "<hr/>" + self.get_argument(f, default=None, strip=False)
self.write(details)
else:
self.set_status(400)
self.write(form.errors)
if __name__ == "__main__":
application = tornado.web.Application(
tornadio2.TornadioRouter(SocketConnection).apply_routes([
(r"/simple", SimpleForm),
]),
)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()