使用wtforms
和tornado
的结合,可以获取到请求的参数,并且对参数进行验证。
from wtforms_tornado import Form
from wtforms import StringField, IntegerField, TextAreaField
from wtforms.validators import DataRequired, Length
class StudentForm(Form):
"""
可以作为student的 post 和 put 的表单使用。
"""
id = IntegerField("id", null=True)
name = StringField("姓名", validators=[DataRequired("请输入姓名")])
age = IntegerField("年龄", validators=[DataRequired("请输入年龄")])
desc = TextAreaField("个人简介", validators=[DataRequired("请输入个人简介")])
然后通过form接收参数,对参数进行验证,验证通过则操作model,对数据库进行保存操作
通过遍历student_from.errors
得到校验失败的字段,然后再返回到前端提示。
代码: apps/school/handler.py
import tornado
from apps.school.forms import StudentForm
from apps.school.models import Student
from tornado_learning.handler import BaseHandler
class StudentHandler(BaseHandler):
async def post(self):
ret_data = {}
student_form = StudentForm(self.request.arguments)
if student_form.validate():
await self.application.objects.create(Student, **student_form.data)
ret_data["ret"] = "success"
else:
for field in student_form.errors:
ret_data[field] = ret_data.errors[field][0]
return self.finish(ret_data)
还可以通过wtforms创建对应的model模板表单。
个人不是很推荐使用,因为前后端耦合性太强。
获取表单
代码: apps/school/forms.py
class StudentFormHandler(BaseHandler):
def get(self):
studentForm = StudentForm()
return self.render("student.html", studentForm=studentForm)
表单的html模板
将该文件放在templates路径下
代码: templates/student.html
<form action="/student" , method="post">
{% autoescape None %}
{% for field in studentForm %}
<span>{{ field.label.text }} :</span>
{{ field(placeholder="请输入"+field.label.text) }}
{% if field.errors %}
{% for error_msg in field.errors %}
<div class="error-msg">{{ error_msg }}</div>
{% end %}
{% else %}
<div class="error-msg"></div>
{% end %}
{% end %}
<label>
<span> </span>
<input type="submit" class="button" value="提交"/>
</label>
</form>
</body>
</html>
需要在设置项中设置模板路径
代码:tornado_learning/settings.py
settings = {
"template_path": "templates"
}
使用wtforms_json
可以使表单直接对json参数的读取。
初始化wtforms_json
首选需要对wtforms_json初始化。
代码: server.py
import wtforms_json
wtforms_json.init()
在handler中获取json参数,然后读入到form中
代码: apps/school/handler.py
class TeacherHandler(BaseHandler):
async def post(self):
ret_data = {}
param = self.request.body.decode("utf8")
param = json.loads(param)
teacherForm = TeacherForm.from_json(param)
print(teacherForm.data)
if teacherForm.validate():
teacher = await self.application.objects.create(Teacher, **teacherForm.data)
ret_data["ret"] = "success"
else:
for field in teacherForm.errors:
ret_data[field] = teacherForm.errors[field][0]
return self.finish(ret_data)