惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
Y
Y Combinator Blog
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
M
MIT News - Artificial intelligence
Last Week in AI
Last Week in AI
V
V2EX
腾讯CDC
F
Fortinet All Blogs
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss

郑文峰的博客

使用dify对接飞书多维表格 使用n8n对接飞书多维表格 服务启动时出现 OOM 一次服务升级时pg表DDL执行超时失败 Go语言高效IO缓冲技术详解 Go语言延迟初始化(Lazy Initialization)最佳实践 Go语言字符串拼接性能对比与优化指南 Go语言结构体内存对齐完全指南 Go语言空结构体:零内存消耗的高效编程 Go语言堆栈分配与逃逸分析深度解析 Go语言原子操作完全指南 Go语言内存预分配完全指南 Go语言不可变数据共享:无锁并发编程实践 Go语言零拷贝技术完全指南 Go语言遍历性能深度解析:从原理到优化实践 Go语言Interface Boxing原理与性能优化指南 Go协程池深度解析:原理、实现与最佳实践 使用etcd分布式锁导致的协程泄露与死锁问题 基于pre-commit的Python代码规范落地实践 初识 MCP Server pulsar阻塞导致logstash无法接入日志 django-prometheus使用及源码分析 kube-proxy源码分析 kubernetes service如何通过iptables转发 tcp缓存引起的日志丢失 django-apschedule定时任务异常停止 理解calico容器网络通信方案原理 理解flannel的三种容器网络方案原理 理解Linux IPIP隧道 理解VXLAN网络
tornado 结合wtforms使用表单操作
zhengwenfeng · 2022-08-10 · via 郑文峰的博客

# 简介

在获取请求时,需要将请求的参数进行验证。
使用wtformstornado的结合,可以获取到请求的参数,并且对参数进行验证。

该项目的github地址: tornado_learning.git (opens new window)

# 例子

创建student的form

代码: apps/shchool/forms.py


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("请输入个人简介")])

1
2
3
4
5
6
7
8
9
10
11
12
13
14

然后通过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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# html表单

还可以通过wtforms创建对应的model模板表单。

个人不是很推荐使用,因为前后端耦合性太强。

获取表单

代码: apps/school/forms.py

class StudentFormHandler(BaseHandler):

    def get(self):
        studentForm = StudentForm()
        return self.render("student.html", studentForm=studentForm)

1
2
3
4
5

表单的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>&nbsp;</span>
        <input type="submit" class="button" value="提交"/>
    </label>
</form>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

需要在设置项中设置模板路径
代码:tornado_learning/settings.py

settings = {
    "template_path": "templates"
}

1
2
3

# wtforms 读取json

使用wtforms_json可以使表单直接对json参数的读取。

初始化wtforms_json

首选需要对wtforms_json初始化。
代码: server.py

import wtforms_json
wtforms_json.init()

1
2

在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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20